Rails/Rspec:测试delayed_job 邮件 [英] Rails/Rspec: Testing delayed_job mails
问题描述
只是想知道如何测试 actionmailer 请求实际上发送到了 rspec 中的延迟作业队列.
Just wondering how to test that actionmailer requests are actually sent to the delayed_job que in rspec.
我会认为这很简单,但我的 delay_job 队列似乎没有增加.代码如下:
I would have assumed it was quite simple, but my delayed_job queue doesn't seem to be incrementing. Code below:
控制器:
def create
@contact = Contact.new(params[:contact])
if @contact.save
contactmailer = ContactMailer
contactmailer.delay.contact_message(@contact)
redirect_to(contacts_url)
else
render :action => "new"
end
规格:
it "queues mail when a contact is created" do
expectedcount = Delayed::Job.count + 1
Contact.stub(:new).with(mock_contact()) { mock_contact(:save => true) }
post :create, :contact => mock_contact
expectedcount.should eq(Delayed::Job.count)
end
在调用控制器之前和之后,Delayed::Job.count 都返回 0.我已经尝试从控制器中取出条件,但我仍然无法使延迟的作业计数增加.
Both before and after the call to the controller, the Delayed::Job.count returns 0. I've tried taking the conditional out of the controller, but I still can't get the delayed job count to increment.
感谢任何建议 - 加油
Any suggestions appreciated - cheer
推荐答案
您还可以通过运行作业或关闭排队来测试作业将执行的操作.
You can also test what the jobs will do by running them or turning off queuing.
随时调整配置(即在 before :each
块中).
Tweak config whenever you want (i.e. in a before :each
block).
Delayed::Worker.delay_jobs = false
或执行您保存的作业
Delayed::Worker.new.work_off.should == [1, 0]
我已经愉快地使用这种方法有一段时间了.一方面,使用 RSpec 中新的 any_instance
支持,您可以直接测试延迟方法的效果.但是,我发现使用 work_off
的测试慢.
I have been using this method happily for a while. For one thing, using the new any_instance
support in RSpec, you can test your delayed methods effects directly. However, I've found tests that use work_off
to be slow.
我现在通常做的是:
mock_delay = double('mock_delay').as_null_object
MyClass.any_instance.stub(:delay).and_return(mock_delay)
mock_delay.should_receive(:my_delayed_method)
然后我有一个单独的 my_delayed_method
规范.这要快得多,而且可能是更好的单元测试实践——尤其是对于控制器.但是,如果您正在制定请求规范或其他集成级别的规范,那么您可能仍然希望使用 work_off
.
Then I have a separate spec for my_delayed_method
. This is much faster, and probably better unit testing practice -- particularly for controllers. Though if you're doing request specs or other integration-level specs, then you probably still want to use work_off
.
这篇关于Rails/Rspec:测试delayed_job 邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!