gpt4 book ai didi

ruby-on-rails - 如何在 RSpec 中多次说 "any_instance" "should_receive"

转载 作者:行者123 更新时间:2023-11-28 19:38:11 24 4
gpt4 key购买 nike

我在 Rails 中有一个导入 Controller ,可以将多个包含多条记录的 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>

Controller 的人为示例:

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 对此进行测试,或者是否有任何解决方法?

最佳答案

这是一个更好的答案,可以避免重写 :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

似乎 stub 方法可以附加到任何没有约束的实例,并且 do block 可以进行计数,您可以检查该计数以断言它被调用了正确的次数。

更新 - 新的 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

关于ruby-on-rails - 如何在 RSpec 中多次说 "any_instance" "should_receive",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9800992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com