Ruby on rails 在改变计数器的操作后测试Rspec
我有我正在测试的控制器Ruby on rails 在改变计数器的操作后测试Rspec,ruby-on-rails,rspec,rspec-rails,Ruby On Rails,Rspec,Rspec Rails,我有我正在测试的控制器 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.orig
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测试:
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
由于某些原因,我在运行测试时出现以下错误:
expected `short_link.view_count` to have changed by 1, but was changed by 0
我的逻辑工作正常,因为我可以看到它将单个链接视图计数增加1,但不是我的测试。当您使用
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)}
同时,如前所述,您的rspec测试没有呼叫
after_action :increment_view_count, only: :redirect_to_original_url
在控制器中(通过从重定向到原始url函数调用增量查看计数函数并运行测试来检查) 由于创建了
short\u link
变量,您需要重新加载该变量以检查值是否已更改。除非重新加载,否则它将存储以前的值
expect { subject }.to change{ short_link.reload.view_count }.by(1)
测试中是否调用了
增量视图\u count
的after\u action
?您可以在该函数中放置调试器或放置。@JakeWorth是的,它被称为nice!在测试中调用主题前后的计数是多少?您可以通过将“expect”替换为只打印计数、调用操作,然后再次打印计数来解决此问题。它仍然是0。这就是为什么它很奇怪。我想我可能需要重新加载,但这不起作用。请尝试change{short\u link.reload.view\u count}
expect { subject }.to change{ short_link.reload.view_count }.by(1)