【发布时间】: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 并且确实如此。问题出在received 或have_received 方法中。
【问题讨论】:
标签: rspec ruby-on-rails-5 rake-task