【发布时间】:2013-01-18 15:26:58
【问题描述】:
标题不言自明。
我尝试过的一切都导致了“未定义的方法”。
澄清一下,我并不是要测试辅助方法。我正在尝试在集成测试中使用辅助方法。
【问题讨论】:
标签: ruby-on-rails rspec
标题不言自明。
我尝试过的一切都导致了“未定义的方法”。
澄清一下,我并不是要测试辅助方法。我正在尝试在集成测试中使用辅助方法。
【问题讨论】:
标签: ruby-on-rails rspec
你只需要在你的测试中包含相关的帮助模块来使方法可用:
describe "foo" do
include ActionView::Helpers
it "does something with a helper method" do
# use any helper methods here
就这么简单。
【讨论】:
SearchHelper::formatResultDate(r.date) 和formatResultDate(r.date),但又得到了另一个“未定义的方法”。谢谢
SearchHelper 是一个模块吗?如果是这样,只需将inlucde ActionView::Helpers 替换为include SearchHelper,然后您应该可以使用formatResultDate(r.date) 调用该方法。
expect(mail.body).to match(I18n.t('some.path', argument: link_to(value, custom_url_helper(value))).
对于迟到此问题的任何人,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
【讨论】:
To clarify, I am not trying to test a helper method.
基于Thomas Riboulet's post on Coderwall:
在您的规范文件的开头添加:
def helper
Helper.instance
end
class Helper
include Singleton
include ActionView::Helpers::NumberHelper
end
然后使用helper.name_of_the_helper 调用特定助手。
此特定示例包括ActionView's NumberHelper。我需要UrlHelper,所以我做了include ActionView::Helpers::UrlHelper 和helper.link_to。
【讨论】:
正如您在此处看到的 https://github.com/rspec/rspec-rails ,您应该使用以下命令初始化 spec/ 目录(规范所在的位置):
$ 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/helpers/。鉴于您正在使用 rspec-rails gem,这将为您提供一个 helper 方法,允许您在其上调用任何辅助方法。
the official rspec-rails documentation 中有一个很好的例子:
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
【讨论】: