【问题标题】:How to include routing in ApplicationHelper Spec when running trough Spork?通过 Spork 运行时如何在 ApplicationHelper Spec 中包含路由?
【发布时间】:2013-04-08 23:49:56
【问题描述】:

我有一个 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 ApplicationHelper
  def link_to_cart
    link_to "Cart", cart_path
  end
end

这在访问该站点时有效,但规范失败,出现关于路由不可用的 RuntimeError:

RuntimeError:
   In order to use #url_for, you must include routing helpers explicitly. For instance, `include Rails.application.routes.url_helpers

所以,我在我的规范中包含了 Rails.application.routes.urlspec_helper 文件,甚至是 ApplicationHelper 本身,但无济于事。

编辑:我正在通过 spork 运行测试,可能与它有关并导致问题。

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

【问题讨论】:

    标签: rspec helper rails-routing spork


    【解决方案1】:

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

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

    # spec/spec_helper.rb
    
    RSpec.configure do |config|
      ...
      config.include Rails.application.routes.url_helpers
      ...
    end
    

    这会加载一个名为“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
    

    我希望这对某人有帮助!

    【讨论】:

      【解决方案2】:

      我将guardspring 一起使用,我发现问题是由弹簧引起的。运行spring stop 后,它已修复。但有时当我在 ApplicationController 中更改某些内容时,它会不断回来。

      【讨论】:

        【解决方案3】:

        您需要在ApplicationHelper 的模块级别添加include,因为ApplicationHelper 默认不包含url 助手。像这样的代码

        module AppplicationHelper
          include Rails.application.routes.url_helpers
        
          # ...
          def link_to_cart
            link_to "Cart", cart_path
          end
        
         end
        

        然后代码就可以工作了,你的测试就通过了。

        【讨论】:

        • 我已经尝试过了,但它没有使测试通过:失败消息保持不变。
        • @berkes,在发布答案之前,我已经在控制台中验证了这一点。有用。在您的问题中,我只看到您提到将其包含在测试中,而不是 ApplicationHelper 模块。这是不正确的。
        • 也不是ApplicationController,而是ApplicationHelper
        • 我错了;问题中的一个错误,但它对我的问题几乎没有改变。我怀疑 spork 是这里的问题,并将尝试将其移出并重新测试。
        • @berkes,我不使用 Spork,而是使用普通的 Rspec。我刚刚用相同的代码为静态页面编写了助手测试。它通过了。不知道为什么会出错。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-09
        • 1970-01-01
        • 2015-03-07
        • 1970-01-01
        • 1970-01-01
        • 2022-06-28
        • 1970-01-01
        相关资源
        最近更新 更多