factory_bot_rails 存根模型不允许在 rails 上访问数据库 ruby
factory_bot_rails stubbed models are not allowed to access the database ruby on rails
我写测试的经验不多所以如果问题不够准确请提前道歉,所以我正在写一些规范突然开始收到stubbed models are not allowed to access the database
,我意识到这是由于流程在特定规范上,类似于 book.update_column(:title, 'El principito')
,所以我环顾四周,似乎 factory_bot_rails 没有存根来自 update_column
的响应,问题是我需要使用 update_column
因为我不想在这个流程上触发回调,关于如何完成这个有什么想法吗?
(为了能够成功 运行 规格,我设法稍微改变了流程,但我不喜欢这种方法)
我的堆栈:rails 5.2.3,ruby 2.6.3,RSpec
提前致谢!
要使用 Factory bot 更新对象,您需要使用 create in factories。示例:
FactoryBot.create(:book)
如果您使用 build_stubbed 创建,您将收到此错误。
FactoryBot.build_stubbed(:book)
我假设您已经使用 build_stubbed
方法构建模型实例。
所以如果你想更新它而不想保存就这样做。
book.title = 'El principito'
如果您想使用update, save or update_column
方法,则记录必须保存在数据库中。在这种情况下,不是存根,而是使用 create
方法
创建书籍记录
create(:book, title: 'ABC')
现在您可以使用 update, save and update-column methods
我写测试的经验不多所以如果问题不够准确请提前道歉,所以我正在写一些规范突然开始收到stubbed models are not allowed to access the database
,我意识到这是由于流程在特定规范上,类似于 book.update_column(:title, 'El principito')
,所以我环顾四周,似乎 factory_bot_rails 没有存根来自 update_column
的响应,问题是我需要使用 update_column
因为我不想在这个流程上触发回调,关于如何完成这个有什么想法吗?
(为了能够成功 运行 规格,我设法稍微改变了流程,但我不喜欢这种方法)
我的堆栈:rails 5.2.3,ruby 2.6.3,RSpec
提前致谢!
要使用 Factory bot 更新对象,您需要使用 create in factories。示例:
FactoryBot.create(:book)
如果您使用 build_stubbed 创建,您将收到此错误。
FactoryBot.build_stubbed(:book)
我假设您已经使用 build_stubbed
方法构建模型实例。
所以如果你想更新它而不想保存就这样做。
book.title = 'El principito'
如果您想使用update, save or update_column
方法,则记录必须保存在数据库中。在这种情况下,不是存根,而是使用 create
方法
create(:book, title: 'ABC')
现在您可以使用 update, save and update-column methods