rspec - 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
并且确实如此。这是问题所在received
或have_received
方法。
解决方案
问题是
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])
现在其余的存根应该可以工作了。
推荐阅读
- android - React Native - 位置“绝对”在Android中不起作用
- codeigniter - 我应该向作曲家提供哪些 Codeigniter 目录以创建技术文档?
- python - python中矩阵的逻辑乘法
- sql - MsAccess - 行到列转置
- selenium - 如何在硒中的窗口之间切换?
- c# - C# 如何在没有编译的情况下在 Razor 视图中运行?
- python-3.x - 仅在图形工具中绘制最大的连通子图
- python - 在 Pandas Python 中连接字符串数据
- java - Apache Camel 上下文删除路由定义方法
- tomcat - Nginx 作为使用 Kerberos 的应用程序的负载均衡器