Ruby-on-rails 未定义的局部变量或方法“root_path”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22741975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:29:06  来源:igfitidea点击:

undefined local variable or method `root_path'

ruby-on-railsruby-on-rails-4rspec

提问by user3389436

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

我的 rspec 文件中有以下代码块位于 /spec 文件夹的根目录。

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?

这没有任何意义。当我遵循 rails 教程时,类似的设置工作得很好。任何人都可以帮忙吗?

EDIT:

编辑:

My routes includes

我的路线包括

root "static#home"

EDIT 2:

编辑2:

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

重新打开这个话题。将我的根声明移到顶部并没有解决它。

EDIT 3:

编辑 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?

有效的是在我的 rspec 配置中包含 url_helpers。我以前从来没有这样做过。谁能回答为什么这有效?

回答by Gergo Erdosi

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

默认情况下,命名路由在规范中不可用。将以下代码添加到spec_helper.rb

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

回答by Lenin Raj Rajasekaran

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

在你的 routes.rb 中,看看你是否定义了root. 像这样的东西:

root :to => 'home#index'

回答by user664833

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_pathand home_urlas named helpers in your application, whereas root_pathand root_urlwill be undefined.

这将在您的应用程序中创建home_pathhome_url作为命名助手,而root_pathandroot_url将是undefined

回答by Richard Peck

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

正如 所提到的@emaillenin,您需要root to: "controller#action"routes.rb文件中包含

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

但是,您需要确保正确声明它 - 我之前已经root_path找到它了,只是因为它在routes.rb文件的末尾或其他东西

It would be beneficial to show your entire routes.rbfile

显示您的整个routes.rb文件将是有益的