【问题标题】:Testing Rspec after_action that changes counter测试改变计数器的 Rspec after_action
【发布时间】:2019-07-15 03:12:49
【问题描述】:

我有我正在尝试测试的控制器。

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

这是redirect_to_original_url的路由:

get 's/:short_url', to: 'short_links#redirect_to_original_url', as: 'redirect_to_original_url'

还有我的 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

我的逻辑有效,因为我可以看到它将单个链接 view_count 增加 1,但不是我的测试。

【问题讨论】:

  • 您的测试中是否调用了increment_view_countafter_action?您可以通过在该函数中放置一个调试器或puts 来了解这一点。
  • @JakeWorth 是的,它正在被调用
  • 不错!在测试中调用主题之前和之后的计数是多少?您可以通过将“期望”替换为仅打印计数、调用操作,然后再次打印计数来解决此问题。
  • 它仍然是 0。这就是为什么它很奇怪。我想也许我需要重新加载,但这没有用。
  • 试试change{ short_link.reload.view_count }

标签: ruby-on-rails rspec rspec-rails


【解决方案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 函数调用 increment_view_count 函数并运行您的测试来检查这一点)。

【讨论】:

    【解决方案2】:

    由于您创建了short_link 变量,您需要重新加载它以检查值是否已更改。除非重新加载它会存储以前的值。

    expect { subject }.to change{ short_link.reload.view_count }.by(1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多