代码之家  ›  专栏  ›  技术社区  ›  ybakos

如何测试依赖Desive signed_in的Rails 5帮助程序?助手,用迷你测试?

  •  0
  • ybakos  · 技术社区  · 6 年前

    给定以下Rails 5帮助器方法,它依赖于Desive帮助器 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
    

    以及希望测试助手是否基于用户的登录状态返回特定链接:

    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
      # ..
    

    你签到了吗? 方法,使其返回 false 第二次测试?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Raj    6 年前

    您需要存根所有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