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

标签 ruby-on-rails testing rspec mocking mocha.js

我在 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/

相关文章:

testing - 在 Hudson 中使用多个代理进行自动测试

go - 在 Golang 中测试 Log 语句输出

rspec - 以默认顺序运行一些 RSpec 文件

javascript - 没有 Javascript 的 capybara Click_Button 失败

ruby-on-rails - 在 Rails 中渲染 JSON 错误时不存在空格

mysql - Ruby on Rails IF 语句验证检查

windows - polymer 测试在 Windows 机器上永无止境

ruby-on-rails - 如何使用 RSpec 测试 ajax POST 请求?

css - Bootstrap img 高度 : auto property overrides explicit height

ruby-on-rails - 与 Thinking Sphinx 的深度关联和 Sphinx 索引?