Rspec allow_any_instance_of 到 return 实例 ID

Rspec allow_any_instance_of to return instance id

是否可以做这样的事情???

allow_any_instance_of(Object).to receive(:foo).and_return("hello #{instance.id}")

我可以 return 消息吗?

使用gem如factory_girlfabrication生成测试对象。

那会让你做...

this_object = Fabricate(:object)
expect(this_object).to receive(:foo).and_return("hello #{this_object.id}")

是的,使用匹配器的 "block" 形式,它使您可以访问实例作为块的形式参数。您还需要确保 Object(或您传递给 allow... 的任何 class)实现 :foo(或您指定的任何方法)作为实例方法,或者allow... 会引发错误。同样,当然,您需要确保 id 也已实现。

下面是一些使用 Object 本身的示例代码:

class Object
  def id
    'bar'
  end
  def foo
  end
end
describe '' do
  it '' do
    allow_any_instance_of(Object).to receive(:foo) { |o| "hello #{o.id}" }
    puts Object.new.foo
  end
end