2

你将如何测试这门课?您会将它与 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
4

1 回答 1

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
于 2013-01-28T16:59:37.280 回答