如何在Rails中测试助手?

aro*_*ick 38 ruby ruby-on-rails helpers

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

Eug*_*kov 38

在rails 3中你可以做到这一点(实际上它是生成器创建的):

require 'test_helper'

class YourHelperTest < ActionView::TestCase
  test "should work" do
    assert_equal "result", your_helper_method
  end
end
Run Code Online (Sandbox Code Playgroud)

当然,Matt Darby的rspec变体也适用于rails 3


Mat*_*rby 28

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

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

describe FoosHelper do

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

end
Run Code Online (Sandbox Code Playgroud)

  • 什么是帮手?我得到`未定义的局部变量或方法`. (2认同)

aro*_*ick 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
Run Code Online (Sandbox Code Playgroud)

[来自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
Run Code Online (Sandbox Code Playgroud)


con*_*com 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
Run Code Online (Sandbox Code Playgroud)