undefined local variable or method `root_path'

2020-02-26 04:26发布

问题:

I have the following block of code in my rspec file located in the root of the /spec folder.

require 'spec_helper'

describe "home" do

 subject { page }

 before(:each) { visit root_path }

 describe "page" do
 it { should have_title('My Page')}
 end

end

When I run it I get

undefined local variable or method `root_path'

Which doesn't make any sense. When I followed the rails tutorial a similar set up worked just fine. Can anyone help?

EDIT:

My routes includes

root "static#home"

EDIT 2:

Reopening this topic. Moving my root declaration to the top did not fix it.

EDIT 3:

What worked was including url_helpers in my rspec config. I've never had to do this before. can anyone answer why this worked?

回答1:

Named routes are not available in specs by default. Add the following code to spec_helper.rb:

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


回答2:

In your routes.rb, see if you have defined root. Something like this:

root :to => 'home#index'


回答3:

You figured out your issue, though I want to let others know that another reason they may get the error message...

NameError: undefined local variable or method `root_path'

...is because they renamed the "root" route:

For example:

root to: 'pages#landing', as: :home

This will create home_path and home_url as named helpers in your application, whereas root_path and root_url will be undefined.



回答4:

As mentioned by @emaillenin, you'll need to include root to: "controller#action" in your routes.rb file

However, you need to ensure this is declared correctly - I've had it before that root_path is not found, only because it's at the end of the routes.rb file or something

It would be beneficial to show your entire routes.rb file