如何测试依赖于Devise signed_in的Rails 5帮助程序? Minitest的帮助者?

时间:2018-11-28 07:50:01

标签: ruby-on-rails testing devise

给出以下依赖于Devise帮助器signed_in?的Rails 5帮助器方法:

module ApplicationHelper
  def sign_in_or_out_link
    if signed_in?
      link_to 'Sign Out', destroy_user_session_path, method: :delete
    else
      link_to 'Sign In', new_user_session_path
    end
  end
end

并且希望根据用户的登录状态测试助手是否返回特定链接:

require 'test_helper'

class ApplicationHelperTest < ActionView::TestCase
  test 'returns Sign Out when signed in' do
    assert_match 'Sign Out', sign_in_or_out_link
  end

  test 'returns Sign In when not signed in' do
    assert_match 'Sign In', sign_in_or_out_link
  end
end

测试运行程序引发错误: NoMethodError: undefined method 'signed_in?' for #<ApplicationHelperTest:...>

虽然我们可以在测试中对方法进行存根:

class ApplicationHelperTest < ActionView::TestCase

  def signed_in?
    true
  end
  # ..

如何重新存根signed_in?方法,使其在第二次测试中返回false

1 个答案:

答案 0 :(得分:2)

您需要对所有3种方法进行存根处理,并使用实例变量来控制两种不同状态的值:

require 'test_helper'

class ApplicationHelperTest < ActionView::TestCase

  def signed_in?
    @signed_in
  end

  def new_user_session_path
    '/users/new'
  end

  def destroy_user_session_path
    '/users/new'
  end

  test 'returns Sign Out when signed in' do
    @signed_in = true
    assert_match 'Sign Out', sign_in_or_out_link
  end

  test 'returns Sign In when not signed in' do
    @signed_in = false
    assert_match /Sign In/, sign_in_or_out_link
  end

end

两项测试均通过:

~/codebases/tmp/rails-devise master*
❯ rake test
Run options: --seed 28418

# Running:

..

Finished in 0.007165s, 279.1347 runs/s, 558.2694 assertions/s.
2 runs, 4 assertions, 0 failures, 0 errors, 0 skips