首页 > 解决方案 > rake 任务 rspec 测试不响应 :have_received 方法

问题描述

我有一个非常简单的 rake 任务:

namespace :subscriptions do
  desc 'Send expired subscription notifications'
  task notify_trial_expired: :environment do
    Subscription.where(expires_at: Date.today.all_day).each { |s| s.user.notify_trial_expired }
  end
end

notify_trial_expired模型的实例方法在哪里User。该任务工作正常,手动测试。

现在使用 rspec 这是我写的:

require 'rails_helper'

describe "notify_trial_expired" do
  let!(:subscription) { create(:subscription, expires_at: Date.today) }
  let(:user) { double(:user) }

  before do
    allow(subscription).to receive(:user) { user }
    allow(user).to receive(:notify_trial_expired)
    Rake.application.rake_require "tasks/subscriptions"
    Rake::Task.define_task(:environment)
    Rake::Task['subscriptions:notify_trial_expired'].invoke
  end

  it "should notify all user which trial expires today" do
    expect(user).to have_received(:notify_trial_expired)
  end
end

我也尝试过expect(user).to receive并在之后调用该任务,但两种方式都显示相同的错误:

Failure/Error: expect(user).to have_received(:notify_trial_expired)

       (Double :user).notify_trial_expired(*(any args))
           expected: 1 time with any arguments
           received: 0 times with any arguments

我还检查以确保查询Subscription.where(expires_at: Date.today.all_day)返回 mysubscription并且确实如此。这是问题所在receivedhave_received方法。

标签: rspecruby-on-rails-5rake-task

解决方案


问题是

allow(subscription).to receive(:user) { user }

此处的对象subscription与您的查询返回的对象不同:Subscription.where(expires_at: Date.today.all_day)。是的,实际上它们是相同的记录,但不是从测试的角度来看(object_id 不同)。

您的查询看起来很简单,所以我将它存根(或将其移动到模型范围并在那里进行测试)。

allow(Subscription).to receive(:where).with(expires_at: Date.today).and_return([subscription])

现在其余的存根应该可以工作了。


推荐阅读