你将如何测试这门课程?你会将它与Resque集成并检查作业是否被放入队列中,或者你会模拟它,如果你想模仿它,你将如何避免重复代码,如示例规范中所示。
class BookingReminderEnqueuer
def initialize(user, booking, worker = BookingReminder)
@user, @booking, @worker = user, booking, worker
end
def enqueue
Resque.enqueue_at(
remind_user_at,
@worker,
booking_id: @booking.id,
user_id: @user.id
) if @booking.remind_user?
end
private
def remind_user_at
@booking.start_time - 6.hours
end
end
require 'spec_helper'
describe BookingReminderEnqueuer
describe "#enqueue" do
context "when the user should have a reminder" do
it "enqueues the reminder" do
booking.stub(:remind_user?) { true }
Resque.should_receive(:enqueue_at).with(
booking.start_time - 6.hours,
BookingReminder,
booking_id: booking.id,
user_id: user.id
).once
booking_reminder_enqueuer.enqueue
end
end
context "when the user shouldn't have a reminder" do
it "does not enqueue the reminder" do
booking.stub(:remind_user?) { false }
Resque.should_not_receive(:enqueue_at)
end
end
end
end
答案 0 :(得分:4)
我会使用类似fakeredis的gem来创建测试redis数据库。这将创建一个隔离的内存Redis实例用于测试,可以在测试运行时清除。然后,您可以使用正确的参数验证作业是否正确排队与模拟排队方法(因为使排队参数正常工作是此方法的核心。
# Gemfile
group :test do
gem "rspec"
gem "fakeredis", :require => "fakeredis/rspec"
end
# Spec
describe BookingReminderEnqueuer
describe "#enqueue" do
context "when the user should have a reminder" do
it "enqueues the reminder" do
booking.stub(:remind_user?) { true }
booking_reminder_enqueuer.enqueue
resque_job = Resque.peek(:queue_name)
resque_job.should be_present
# add assertions about job content/scheduling here
end
end
...
end
end