我在rails中有一个导入控制器,它将多个带有多条记录的csv文件导入到我的数据库中。我想在RSpec中测试是否使用RSpec实际保存了记录:
<Model>.any_instance.should_receive(:save).at_least(:once)
但是我得到的错误是:
The message 'save' was received by <model instance> but has already been received by <another model instance>
控制器的一个人为举例:
rows = CSV.parse(uploaded_file.tempfile, col_sep: "|")
ActiveRecord::Base.transaction do
rows.each do |row|
mutation = Mutation.new
row.each_with_index do |value, index|
Mutation.send("#{attribute_order[index]}=", value)
end
mutation.save
end
是否可以使用RSpec进行测试或是否有解决方法?
答案 0 :(得分:45)
有一种新的语法:
expect_any_instance_of(Model).to receive(:save).at_least(:once)
答案 1 :(得分:43)
这是一个更好的答案,可以避免必须覆盖:new方法:
save_count = 0
<Model>.any_instance.stub(:save) do |arg|
# The evaluation context is the rspec group instance,
# arg are the arguments to the function. I can't see a
# way to get the actual <Model> instance :(
save_count+=1
end
.... run the test here ...
save_count.should > 0
似乎存根方法可以附加到没有约束的任何实例,并且do块可以进行计数,你可以检查断言它被称为正确的次数。
更新 - 新的rspec版本需要以下语法:
save_count = 0
allow_any_instance_of(Model).to receive(:save) do |arg|
# The evaluation context is the rspec group instance,
# arg are the arguments to the function. I can't see a
# way to get the actual <Model> instance :(
save_count+=1
end
.... run the test here ...
save_count.should > 0
答案 2 :(得分:15)
我终于设法做了一个适合我的测试:
mutation = FactoryGirl.build(:mutation)
Mutation.stub(:new).and_return(mutation)
mutation.should_receive(:save).at_least(:once)
存根方法返回一个多次接收save方法的实例。因为它是单个实例,所以我可以放弃any_instance
方法并正常使用at_least
方法。
答案 3 :(得分:10)
像这样存根
User.stub(:save) # Could be any class method in any class
User.any_instance.stub(:save) { |*args| User.save(*args) }
然后期待这样:
# User.any_instance.should_receive(:save).at_least(:once)
User.should_receive(:save).at_least(:once)
这是this gist的简化,使用any_instance
,因为您不需要代理原始方法。请参阅该要点以供其他用途。
答案 4 :(得分:8)
这是Rob使用RSpec 3.3的示例,它不再支持Foo.any_instance
。我发现这在创建对象的循环中很有用
# code (simplified version)
array_of_hashes.each { |hash| Model.new(hash).write! }
# spec
it "calls write! for each instance of Model" do
call_count = 0
allow_any_instance_of(Model).to receive(:write!) { call_count += 1 }
response.process # run the test
expect(call_count).to eq(2)
end
答案 5 :(得分:2)
我的情况有点不同,但我最终还是想在这个问题上找到答案。在我的情况下,我想要存根给定类的任何实例。我使用expect_any_instance_of(Model).to
时遇到了同样的错误。当我将其更改为allow_any_instance_of(Model).to
时,我的问题就解决了。
查看文档以获取更多背景信息:https://github.com/rspec/rspec-mocks#settings-mocks-or-stubs-on-any-instance-of-a-class
答案 6 :(得分:0)
您可以尝试计算班级上new
的数量。那实际上不是测试save
的数量,但可能足够
expect(Mutation).to receive(:new).at_least(:once)
如果仅预期保存了多少次。然后,您可能想使用spy()
而不是完全发挥作用的工厂,如Harm de Wit
自己的答案
allow(Mutation).to receive(:new).and_return(spy)
...
expect(Mutation.new).to have_received(:save).at_least(:once)