如何从Rails中的RSpec测试中调用app helper方法?
标题是自我解释的。
我尝试过的所有东西都导致了“未定义的方法”。
为了澄清,我不是试图测试辅助方法。 我试图在集成测试中使用辅助方法。
您只需在测试中包含相关的辅助模块即可使方法可用:
describe "foo" do include ActionView::Helpers it "does something with a helper method" do # use any helper methods here
它真的很简单。
对于迟到这个问题的人,可以在Relish网站上找到答案。
require "spec_helper" describe "items/search.html.haml" do before do controller.singleton_class.class_eval do protected def current_user FactoryGirl.build_stubbed(:merchant) end helper_method :current_user end end it "renders the not found message when @items is empty" do render expect( rendered ).to match("Sorry, we can't find any items matching "".") end end
如果您尝试在视图测试中使用辅助方法,则可以使用以下内容:
before do view.extend MyHelper end
它必须在describe
块内。
它适用于rails 3.2和rspec 2.13
基于Thomas Riboulet关于Coderwall的post :
在spec文件的开头添加:
def helper Helper.instance end class Helper include Singleton include ActionView::Helpers::NumberHelper end
然后使用helper.name_of_the_helper
调用特定的帮助helper.name_of_the_helper
。
这个特殊的例子包括ActionView的NumberHelper 。 我需要UrlHelper ,所以我确实include ActionView::Helpers::UrlHelper
和helper.link_to
。
正如你在这里看到的https://github.com/rspec/rspec-rails ,你应该初始化spec /目录(specs将驻留在哪里):
$ rails generate rspec:install
这将生成带有选项的rails_helper.rb
config.infer_spec_type_from_file_location!
最后在helper_spec.rb中需要新的rails_helper而不是’spec_helper’。
require 'rails_helper' describe ApplicationHelper do ... end
祝好运。
我假设你正在尝试测试辅助方法。 为此,您必须将spec文件放入spec/helpers/
。 鉴于您正在使用rspec-rails
gem,这将为您提供一个helper
方法,允许您在其上调用任何帮助方法。
在官方的rspec-rails
文档中有一个很好的例子:
require "spec_helper" describe ApplicationHelper do describe "#page_title" do it "returns the default title" do expect(helper.page_title).to eq("RSpec is your friend") end end end