【问题标题】:Prevent RSpec stub from turning associated object into mock防止 RSpec 存根将关联对象转换为模拟对象
【发布时间】:2014-02-25 06:20:35
【问题描述】:

我最近遇到了一个令我惊讶的是以前从未见过的问题。我有这样的课程:

class Foo < ActiveRecord::Base
  belongs_to :bar, inverse_of: :foos
end

class Bar < ActiveRecord::Base
  has_many :foos, inverse_of: :bar
end

我正在使用fabricators 像这样(我知道这些看起来毫无意义):

Fabricator(:foo, class_name: Foo) do
  bar fabricator: :bar
end

Fabricator(:bar, class_name: Bar) do
end

在测试 (RSpec) 中我正在做这个存根:

foo = Fabricate(:foo) # I can confirm that both foo and foo.bar are correct here.
Foo.stub(:find_by_id).and_return(foo)

我的问题是在测试中,当调用Foo.find_by_id 时,它会正确返回foofoo.bar 是一个RSpec 模拟,保存foo 会导致此错误消息:

Mock received unexpected message :marked_for_destruction? with (no args)

如何确保关联也通过存根传递?我找到了this thread,但无法完全理解它的含义。

任何帮助将不胜感激!

【问题讨论】:

    标签: ruby-on-rails rspec fabrication-gem


    【解决方案1】:

    当然,我的问题是后来在测试中我调用了Foo.stub_chain(:bar, :property),所以foo.bar 自然只是一个 RSpec Mock。

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 2021-07-02
      • 2021-12-08
      • 1970-01-01
      • 2021-03-22
      • 2011-05-19
      相关资源
      最近更新 更多