如何使用 RSpec 测试delayed_job回调钩子
我想验证delayed_job回调钩子是否被调用,但我不知道如何让RSpec来做到这一点,特别是当涉及多层类时。
假设我有一个像这样的 ActiveRecord 模型:
class MyJob < ActiveRecord::Base
def perform
# do some stuff
end
def after(job)
# called by delayed_job after perform completes
end
end
概念上,我想要沿着这些线进行 RSpec 测试(尽管我知道这是不正确的):
it 'should call the :after callback hook' do
my_job = MyJob.create
my_job.should_receive(:after).with(an_instance_of(Delayed::Backend::ActiveRecord::Job))
Delayed::Job.enqueue(my_job)
Delayed::Worker.new.work_off
end
我已经仔细研究了 stackoverflow、relishapp.com/rspec 和我能想到的所有其他地方。这不会太难吧? (我打赌@zetetic 在睡梦中就知道答案……;)
(注意:我的实际案例在 MyJob 和 DJ 之间使用了“shim”类。这个简单案例的答案可能会引发更复杂的后续问题!)
I'd like to verify that delayed_job callback hooks are getting called, but I don't see how to get RSpec to do it, especially when several layers of classes are involved.
Assuming I have an ActiveRecord model like this:
class MyJob < ActiveRecord::Base
def perform
# do some stuff
end
def after(job)
# called by delayed_job after perform completes
end
end
Conceptually, I want an RSpec test along these lines (though I know this isn't correct):
it 'should call the :after callback hook' do
my_job = MyJob.create
my_job.should_receive(:after).with(an_instance_of(Delayed::Backend::ActiveRecord::Job))
Delayed::Job.enqueue(my_job)
Delayed::Worker.new.work_off
end
I've pored over stackoverflow, relishapp.com/rspec and all the other places I can think of. It can't be too hard, right? (I bet @zetetic knows the answer in his sleep... ;)
(Caveat: My actual case uses a 'shim' class between MyJob and DJ. An answer for this simple case may trigger a more complex follow-on!)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
恕我直言,我认为这不是最好的做法...
通过这样做,您正在尝试规范 DelayedJob 的行为,而不是您的应用程序,并且 DJ 已经有了自己的测试套件。
不管怎样,嘲笑 DelayedJob 本身怎么样?也许您可以通过这样做指定您的 MockedJob 将在处理后调用您的钩子,并且您可以相应地创建匹配器/期望...
IMHO i don't think this is the best thing to do...
By doing this, you're trying to spec DelayedJob's behavior, not your app, and DJ already has its own suit of tests.
Anyway, what about mocking DelayedJob itself? Maybe you can specify, by doing that, that your MockedJob will call your hook after processing, and you can create your matchers/expectations accordingly...
我的建议是查看作业表是否创建了新的作业记录,然后内省该记录的详细信息。我过去用过类似的东西。
My suggestion would be to see if the Jobs table creates a new job record, and then introspect the details of that record. I've used something like this in the past.