ruby-on-rails – 带有属性的rspec stub any_instance

我需要存根具有特定属性或属性集的模型的所有实例.例如,使用ActiveRecord:

let(:model1) { Model.create!(uid: 1) }
let(:model2) { Model.create!(uid: 2) }

before do
  allow(model1).to receive(:foo).and_return :bar 
  allow(model2).to receive(:foo).and_return :baz
end

it do
  expect(model1.foo).to eq :bar # => passes
  expect(model2.foo).to eq :baz # => passes

  ################################################
  #### Here is the issue I'm trying to solve: ####
  ################################################
  new_instance_of_model1 = Model.find_by(uid: 1)
  new_instance_of_model2 = Model.find_by(uid: 2)

  expect(new_instance_of_model1.foo).to eq :bar # => fails
  expect(new_instance_of_model2.foo).to eq :baz # => fails
end

有没有办法将所有具有uid的Model实例存根:1?

我正在寻找类似的东西:

allow_any_instance_of(Model).with_attributes(uid: 1).to receive(:foo).and_return(:bar)
allow_any_instance_of(Model).with_attributes(uid: 2).to receive(:foo).and_return(:baz)

注意:

我不能使用像:

allow(Model).to receive(:find).with(1)and_return(model1)
allow(Model).to receive(:find).with(2)and_return(model2)

因为还有很多其他方法可以进入模型(协会,范围,Arel等)

最佳答案 这不是一个好主意,但是您可以通过将块参数传递给receive而不是方法链来完成此操作,如下所示:

allow_any_instance_of(Model).to receive(:foo) do |model|
  case model.uid
  when 1
    :bar
  when 2
    :baz
  end
end
点赞