How do I test helpers in Rails?

后端 未结 5 1480
北海茫月
北海茫月 2021-02-03 18:24

I\'m trying to build some unit tests for testing my Rails helpers, but I can never remember how to access them. Annoying. Suggestions?

相关标签:
5条回答
  • 2021-02-03 18:55

    I just posted this answer on another thread asking the same question. I did the following in my project.

    require_relative '../../app/helpers/import_helper'
    
    0 讨论(0)
  • 2021-02-03 19:01

    This thread is kind of old, but I thought I'd reply with what I use:

    # 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
    
    0 讨论(0)
  • 2021-02-03 19:03

    In rails 3 you can do this (and in fact it's what the generator creates):

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

    And of course the rspec variant by Matt Darby works in rails 3 too

    0 讨论(0)
  • 2021-02-03 19:04

    Stolen from here: 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
    

    [Stolen from Matt Darby, who also wrote in this thread.] You can do the same in RSpec as:

    require File.dirname(__FILE__) + '/../spec_helper'
    
    describe FoosHelper do
    
      it "should do something" do
        helper.some_helper_method.should == @something
      end
    
    end
    
    0 讨论(0)
  • 2021-02-03 19:07

    You can do the same in RSpec as:

    require File.dirname(__FILE__) + '/../spec_helper'
    
    describe FoosHelper do
    
      it "should do something" do
        helper.some_helper_method.should == @something
      end
    
    end
    
    0 讨论(0)
提交回复
热议问题