Question

I have an rspec spec:

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

And the ApplicationHelper:

module ApplicationHelper
  def link_to_cart
    link_to "Cart", cart_path
  end
end

This works when visiting the site, but the specs fail with a RuntimeError about Routing not being available:

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

So, I included the Rails.application.routes.url in my spec, the spec_helper-file and even the ApplicationHelper itself, to no avail.

Edit: I am running the tests via spork, maybe that has to do with it and is causing the issue.

How must I include these route helpers when running with Spork?

Was it helpful?

Solution

You need to add include at module level of ApplicationHelper, because ApplicationHelper doesn't include the url helper by default. Code like this

module AppplicationHelper
  include Rails.application.routes.url_helpers

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

 end

Then the code will work and your test will pass.

OTHER TIPS

If you are using spork with rspec, you should add the url_helper method to your rspec config -

Anywhere inside '/spec/spec_helper' file:

# spec/spec_helper.rb

RSpec.configure do |config|
  ...
  config.include Rails.application.routes.url_helpers
  ...
end

this loads a built-in ApplicationHelper called "Routes" and calls the '#url_helpers' method into RSpec. There is no need to add it to the ApplicationHelper in '/app/helpers/application_helper.rb' for two reasons:

  1. You are just copying 'routes' functionality into a place that doesn't need it, essentially the controller, which already inherits it from ActionController::Base (I think. maybe ::Metal. not important now). so you are not being DRY - Don't Repeat Yourself

  2. This error is specific to RSpec configuration, fix it where it's broke (My own little aphorism)

Next, I'd recommend fixing your test a little. Try this:

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

I hope that this is helpful to someone!

I was using guard with spring and I found out that, in my case, the issue was caused by spring. After running spring stop it was fixed. But it keeps coming back sometimes when I change something in an ApplicationController.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top