作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 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/
我是一名优秀的程序员,十分优秀!