0

Given the following Rails 5 helper method, that relies on the Devise helper signed_in?:

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

And the desire to test that the helper returns a particular link based on the signed-in status of the user:

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

The test runner raises an error: NoMethodError: undefined method 'signed_in?' for #<ApplicationHelperTest:...>.

While we can stub the method within the test:

class ApplicationHelperTest < ActionView::TestCase

  def signed_in?
    true
  end
  # ..

How do I re-stub the signed_in? method such that it returns false for the second test?

ybakos
  • 8,152
  • 7
  • 46
  • 74
  • Basically, this question is: 'how do i stub in mini-test?'. Try some of the answers in this solution: https://stackoverflow.com/questions/7211086/how-do-i-stub-things-in-minitest – BenKoshy Dec 12 '18 at 08:05

1 Answers1

2

You need to stub all 3 methods and use an instance variable to control the value for two different states:

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

Both tests pass:

~/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
Raj
  • 22,346
  • 14
  • 99
  • 142