如何在Spork运行时在ApplicationHelper规范中包含路由?

ber*_*kes 6 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
Run Code Online (Sandbox Code Playgroud)

和ApplicationHelper:

module ApplicationHelper
  def link_to_cart
    link_to "Cart", cart_path
  end
end
Run Code Online (Sandbox Code Playgroud)

这在访问站点时有效,但规范失败,并显示有关路由的RuntimeError不可用:

RuntimeError:
   In order to use #url_for, you must include routing helpers explicitly. For instance, `include Rails.application.routes.url_helpers
Run Code Online (Sandbox Code Playgroud)

因此,我Rails.application.routes.url在我的规范中包含了spec_helper-file,甚至包括ApplicationHelper它本身,都无济于事.

编辑:我正在通过spork运行测试,也许这与它有关并导致问题.

在使用Spork运行时,如何包含这些路线助手?

Bil*_*han 8

您需要include在模块级别添加ApplicationHelper,因为默认情况下ApplicationHelper不包含url帮助程序.像这样的代码

module AppplicationHelper
  include Rails.application.routes.url_helpers

  # ...
  def link_to_cart
    link_to "Cart", cart_path
  end

 end
Run Code Online (Sandbox Code Playgroud)

然后代码将工作,您的测试将通过.

  • @berkes,在发布答案之前,我已经在控制台中进行了验证。有用。在您的问题中,我只看到您提到将其包含在测试中,但没有提到ApplicationHelper模块。那是不对的。 (2认同)

小智 5

如果您将sporkrspec一起使用,您应该将 url_helper 方法添加到您的 rspec 配置中 -

'/spec/spec_helper' 文件中的任何位置:

# spec/spec_helper.rb

RSpec.configure do |config|
  ...
  config.include Rails.application.routes.url_helpers
  ...
end
Run Code Online (Sandbox Code Playgroud)

这会加载一个名为“Routes”的内置 ApplicationHelper,并将“#url_helpers”方法调用到 RSpec 中。出于两个原因,无需将其添加到“/app/helpers/application_helper.rb”中的 ApplicationHelper:

  1. 您只是将“路由”功能复制到不需要它的地方,本质上是控制器,它已经从 ActionController::Base 继承了它(我认为。也许 ::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
Run Code Online (Sandbox Code Playgroud)

我希望这对某人有帮助!