使用 RSpec 和模拟测试 after_commit [英] Testing after_commit with RSpec and mocking
本文介绍了使用 RSpec 和模拟测试 after_commit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模型 Lead 和一个回调:after_commit :create, :send_to_SPL
I have a model Lead and a callback: after_commit :create, :send_to_SPL
我使用的是 Rails-4.1.0、ruby-2.1.1、RSpec.
I am using Rails-4.1.0, ruby-2.1.1, RSpec.
1) 此规范未通过:
context 'callbacks' do
it 'shall call \'send_to_SPL\' after create' do
expect(lead).to receive(:send_to_SPL)
lead = Lead.create(init_hash)
p lead.new_record? # => false
end
end
2) 这个规范也没有通过:
2) This spec is not passing too:
context 'callbacks' do
it 'shall call \'send_to_SPL\' after create' do
expect(ActiveSupport::Callbacks::Callback).to receive(:build)
lead = Lead.create(init_hash)
end
end
3) 这个是通过的,但我认为它没有测试 after_commit 回调:
3) This one is passing, but I think it is not testing after_commit callback:
context 'callbacks' do
it 'shall call \'send_to_SPL\' after create' do
expect(lead).to receive(:send_to_SPL)
lead.send(:send_to_SPL)
end
end
在 Rails 中测试 after_commit 回调的最佳方法是什么?
What is the best way to test after_commit callbacks in Rails?
推荐答案
尝试使用 test_after_commit gem
或在 spec/support/helpers/test_after_commit.rb 中添加以下代码 - Gist
or add following code in spec/support/helpers/test_after_commit.rb - Gist
这篇关于使用 RSpec 和模拟测试 after_commit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文