如何在Rails中测试助手?

时间:2009-01-13 20:06:32

标签: ruby-on-rails ruby helpers

我正在尝试构建一些单元测试来测试我的Rails助手,但我永远不会记得如何访问它们。烦人。建议?

5 个答案:

答案 0 :(得分:37)

在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

答案 1 :(得分:28)

您可以在RSpec中执行相同的操作:

require File.dirname(__FILE__) + '/../spec_helper'

describe FoosHelper do

  it "should do something" do
    helper.some_helper_method.should == @something
  end

end

答案 2 :(得分:11)

从这里被盗: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

答案 3 :(得分:5)

这个帖子有点陈旧,但我想我会用我的用法回复:

# 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

答案 4 :(得分:0)

我刚刚在另一个提出相同问题的帖子上发布了这个答案。我在我的项目中做了以下几点。

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