Ruby-on-rails 如何在 Rails 中测试助手?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/440571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I test helpers in Rails?
提问by aronchick
I'm trying to build some unit tests for testing my Rails helpers, but I can never remember how to access them. Annoying. Suggestions?
我正在尝试构建一些单元测试来测试我的 Rails 助手,但我永远不记得如何访问它们。恼人的。建议?
采纳答案by Eugene Bolshakov
In rails 3 you can do this (and in fact it's what the generator creates):
在 rails 3 中,你可以这样做(实际上这是生成器创建的):
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 Darbyworks in rails 3 too
当然,Matt Darby 的 rspec 变体也适用于 rails 3
回答by Matt Darby
You can do the same in RSpec as:
你可以在 RSpec 中做同样的事情:
require File.dirname(__FILE__) + '/../spec_helper'
describe FoosHelper do
it "should do something" do
helper.some_helper_method.should == @something
end
end
回答by aronchick
Stolen from here: http://joakimandersson.se/archives/2006/10/05/test-your-rails-helpers/
从这里被盗: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:
[从 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
回答by conradkleinespel
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
回答by Shawn Deprey
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'

