【问题标题】:How do I test helpers in Rails?如何在 Rails 中测试助手?
【发布时间】:2010-10-01 05:35:20
【问题描述】:

我正在尝试构建一些单元测试来测试我的 Rails 助手,但我不记得如何访问它们。恼人的。有什么建议吗?

【问题讨论】:

    标签: ruby-on-rails ruby helpers


    【解决方案1】:

    在 Rails 3 中,您可以这样做(实际上它是生成器创建的):

    require 'test_helper'
    
    class YourHelperTest < ActionView::TestCase
      test "should work" do
        assert_equal "result", your_helper_method
      end
    end
    

    当然the rspec variant by Matt Darby 也适用于 rails 3

    【讨论】:

      【解决方案2】:

      你可以在 RSpec 中做同样的事情:

      require File.dirname(__FILE__) + '/../spec_helper'
      
      describe FoosHelper do
      
        it "should do something" do
          helper.some_helper_method.should == @something
        end
      
      end
      

      【讨论】:

      • 现在是这样的时候,我希望我能批准两个答案。您介意将我的答案复制并粘贴到您的答案中吗?我将把它作为这个问题的答案?
      • 什么是助手?我得到undefined local variable or method
      • 我也得到了undefined local variable or method helper,然后我按照relishapp.com/rspec/rspec-rails/v/3-6/docs/helper-specs/… 的说明进行了解决。就我而言,我已经拥有config.infer_spec_type_from_file_location!,但忘记了require 'spec_helper'。希望有帮助!
      【解决方案3】:

      从这里被盗:http://joakimandersson.se/archives/2006/10/05/test-your-rails-helpers/

      require File.dirname(__FILE__) + ‘/../test_helper’
      require ‘user_helper’
      
      class UserHelperTest < Test::Unit::TestCase
      
      include UserHelper
      
      def test_a_user_helper_method_here
      end
      
      end
      

      [从 Matt Darby 那里偷来的,他也在这个帖子中写道。]你可以在 RSpec 中做同样的事情:

      require File.dirname(__FILE__) + '/../spec_helper'
      
      describe FoosHelper do
      
        it "should do something" do
          helper.some_helper_method.should == @something
        end
      
      end
      

      【讨论】:

      • 最好从ActionView::TestCase派生,否则你将无权访问params哈希
      【解决方案4】:

      这个帖子有点老了,但我想我会用我使用的东西来回复:

      # encoding: UTF-8
      
      require 'spec_helper'
      
      describe AuthHelper do
      
        include AuthHelper # has methods #login and #logout that modify the session
      
        describe "#login & #logout" do
          it "logs in & out a user" do
            user = User.new :username => "AnnOnymous"
      
            login user
            expect(session[:user]).to eq(user)
      
            logout
            expect(session[:user]).to be_nil
          end
        end
      
      end
      

      【讨论】:

      • 对使用这个包括 概念的人只有一个警告。如果您不小心将它放在“描述...”之前,它会在单个测试中正常工作,但可能会由于双重包含而弄乱您的测试套件。
      【解决方案5】:

      我刚刚在另一个帖子上发布了这个答案,问了同样的问题。我在我的项目中做了以下操作。

      require_relative '../../app/helpers/import_helper'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-21
        • 1970-01-01
        • 1970-01-01
        • 2019-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多