我有要测试的控制器。
Exception
这是redirect_to_original_url的路由:
class ShortLinksController < ApplicationController
after_action :increment_view_count, only: :redirect_to_original_url
def redirect_to_original_url
link = ShortLink.find(params[:short_url])
redirect_to "http://#{link.original_url}"
end
private
def increment_view_count
ShortLink.increment_counter(:view_count, params[:short_url])
end
end
我的Rspec测试:
get 's/:short_url', to: 'short_links#redirect_to_original_url', as: 'redirect_to_original_url'
由于某种原因,运行测试时出现以下错误:
describe "#redirect_to_original_url" do
let(:short_link) {ShortLink.create(original_url: 'www.google.com')}
subject {get :redirect_to_original_url, params: {short_url: short_link.id}}
it 'should increment the count by 1 original url is visited' do
expect {subject}.to change{ short_link.view_count }.by(1)
end
end
我的逻辑正常工作,因为我看到它使单个链接的view_count增加了1,但没有增加我的测试。
答案 0 :(得分:1)
使用以下方法为ShortLink模型创建对象时,请检查view_count的默认值
let(:short_link) {ShortLink.create(original_url: 'www.google.com')}
//Creating object
it 'should have value 0 when shortlink object is created' do
expect(short_link.view_count).to eq(0)
end
如果此示例失败,则使用view_count的默认值创建对象,
let(:short_link) {ShortLink.create(original_url: 'www.gmail.com',view_count: 0)}
与此同时,Jake Worth说您的rspec测试未调用,
after_action :increment_view_count, only: :redirect_to_original_url
在您的控制器中(通过从redirect_to_original_url函数调用增量视图数量计数并运行测试来对此进行检查)。
答案 1 :(得分:0)
自创建short_link
变量以来,您需要重新加载它以检查值是否已更改。除非重新加载,否则它将存储以前的值。
expect { subject }.to change{ short_link.reload.view_count }.by(1)