【问题标题】:rake task rspec test does not respond to :have_received methodrake 任务 rspec 测试不响应 :have_received 方法
【发布时间】:2019-05-06 17:57:38
【问题描述】:

我有一个非常简单的 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) 返回我的 subscription 并且确实如此。问题出在receivedhave_received 方法中。

【问题讨论】:

    标签: rspec ruby-on-rails-5 rake-task


    【解决方案1】:

    问题是

    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])
    

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

    【讨论】:

      猜你喜欢
      • 2015-12-29
      • 1970-01-01
      • 2014-09-06
      • 2011-10-17
      • 1970-01-01
      • 2011-02-06
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多