Rspec 在运行Spork时,如何在ApplicationHelper规范中包含路由?
我有一个rspec规范:Rspec 在运行Spork时,如何在ApplicationHelper规范中包含路由?,rspec,helper,rails-routing,spork,Rspec,Helper,Rails Routing,Spork,我有一个rspec规范: require "spec_helper" describe ApplicationHelper do describe "#link_to_cart" do it 'should be a link to the cart' do helper.link_to_cart.should match /.*href="\/cart".*/ end end end 以及ApplicationHelper: module Applica
require "spec_helper"
describe ApplicationHelper do
describe "#link_to_cart" do
it 'should be a link to the cart' do
helper.link_to_cart.should match /.*href="\/cart".*/
end
end
end
以及ApplicationHelper:
module ApplicationHelper
def link_to_cart
link_to "Cart", cart_path
end
end
这在访问站点时有效,但规范失败,并出现关于路由不可用的运行时错误:
RuntimeError:
In order to use #url_for, you must include routing helpers explicitly. For instance, `include Rails.application.routes.url_helpers
因此,我在规范中包括了Rails.application.routes.url
、spec\u helper
-文件,甚至ApplicationHelper
本身,但都没有用
编辑:我正在通过spork运行测试,可能这与此有关,并导致了问题
使用Spork运行时,我必须如何包含这些路由帮助程序?您需要在
ApplicationHelper
的模块级别添加include
,因为ApplicationHelper默认不包含url帮助程序。代码是这样的
module AppplicationHelper
include Rails.application.routes.url_helpers
# ...
def link_to_cart
link_to "Cart", cart_path
end
end
然后代码将正常工作,您的测试将通过。如果您使用with,则应将url\u helper方法添加到您的rspec配置中-
在“/spec/spec\u helper”文件中:
RSpec.configure do |config|
.
. =begin
. bunch of stuff here, you can put the code
. pretty much anywhere inside the do..end block
. =end
config.include Rails.application.routes.url_helpers
.
. #more stuff
end
这将加载一个名为“Routes”的内置ApplicationHelper,并将“#url_helpers”方法调用到RSpec中。无需将其添加到“/app/helpers/application\u helper.rb”中的ApplicationHelper,原因有二:
1) 您只是将“路由”功能复制到一个不需要它的地方,本质上是控制器,它已经从ActionController::Base继承了它(我认为.maybe::Metal.现在不重要了)。所以你不是在干——不要重复你自己
2) 这个错误是特定于RSpec配置的,在它坏掉的地方修复它(我自己的小格言)
接下来,我建议您稍微修改一下测试。试试这个:
require "spec_helper"
describe ApplicationHelper do
describe "#link_to_cart" do
it 'should be a link to the cart' do
visit cart_path
expect(page).to match(/.*href="\/cart".*/)
end
end
end
我希望这对某人有帮助 我在使用
guard
和spring
时,发现问题是由spring引起的。运行弹簧止动块后
已修复。但有时当我在应用程序控制器中更改某些内容时,它会不断出现。我已经尝试过了,但它没有通过测试:失败消息保持不变。@berkes,在发布答案之前,我已经在控制台中验证了这一点。它起作用了。在您的问题中,我只看到您提到在测试中包含它,而不是ApplicationHelper模块。这是不正确的。这也不是ApplicationController
,而是ApplicationHelper
我的错;这是问题中的一个错误,但对我的问题几乎没有改变。我怀疑spork是这里的问题,并将尝试将其移出并重新测试。@berkes,我不使用spork,而是使用普通的Rspec。我刚刚用相同的代码为一个静态页面编写了testforhelper。就这样过去了。不知道你为什么会出错。