Failure/Error: visit movies_url NameError: undefined local variable or method `movies_url' for #<RSpec::Core::ExampleGroup::Nested_1:0x007ff450c81800>

Failure/Error: visit movies_url NameError: undefined local variable or method `movies_url' for #<RSpec::Core::ExampleGroup::Nested_1:0x007ff450c81800>

我才刚刚开始 RSpec。当 运行 我的规范文件时,我收到一个未定义的变量或方法 'movies_url' 的错误。这是我 运行 rspec:

时的样子
bundle exec rspec spec/list_movies_spec.rb
F

Failures:

  1) when viewing the list of movies should show the movies
     Failure/Error: visit movies_url
     NameError:
       undefined local variable or method `movies_url' for #<RSpec::Core::ExampleGroup::Nested_1:0x007ff450c81800>
     # ./spec/list_movies_spec.rb:24:in `block (2 levels) in <top (required)>'

Finished in 0.01881 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/list_movies_spec.rb:4 # when viewing the list of movies should show the movies

Randomized with seed 45910

list_movies_spec.rb这是我的测试我是运行ning.

require "spec_helper"

describe "when viewing the list of movies" do
  it "should show the movies" do

movie1 = Movie.create(title: "Iron Man",
                      rating: "PG-13",
                      total_gross: 318412101.00,
                      description: "Tony Stark builds an armored suit to fight the throes of evil",
                      released_on: "2008-05-02")

movie2 = Movie.create(title: "Superman",
                      rating: "PG",
                      total_gross: 134218018.00,
                      description: "Clark Kent grows up to be the greatest super-hero",
                      released_on: "1978-12-15")

movie3 = Movie.create(title: "Spider-Man",
                      rating: "PG-13",
                      total_gross: 403706375.00,
                      description: "Peter Parker gets bit by a genetically modified spider",
                      released_on: "2002-05-03")

    visit movies_url

    expect(page).to have_text("3 Movies")
    expect(page).to have_text("Iron Man")
    expect(page).to have_text("Batman")
    expect(page).to have_text("Captain America")
  end
end

Gemfile 这是我用 Capybara 和 RSpec 版本安装的。

group :test, :development do
  gem "minitest"
  gem "rspec-rails", "2.13.1"
end

group :test do
  gem "capybara", "2.1.0"
end

我确实有符合规范的正确路线 movies_url。

rake routes
Prefix Verb URI Pattern       Controller#Action
movies GET  /movies(.:format) movies#index

在我的主机上 运行:

app.movies_url
=> "http://www.example.com/movies"

我曾在其他地方寻找线索,但没有成功。我认为这是 RSpec 和 Capybara 版本问题?

更多详情:

gem list rspec

*** LOCAL GEMS ***

rspec-core (3.3.1, 2.13.1)
rspec-expectations (3.3.0, 2.13.0)
rspec-mocks (3.3.1, 2.13.1)
rspec-rails (3.3.2, 2.13.1)
rspec-support (3.3.0)

gem list capybara

*** LOCAL GEMS ***

capybara (2.1.0)

将其放入规格文件中。

include Rails.application.routes.url_helpers

上面的代码将使所有 urls 助手在您的测试中可访问,例如 root_path、movies_url。但是要访问我们还应该在 test.rb 环境文件中定义主机。为此,将以下代码放在 test.rb

Rails.application.routes.default_url_options[:host]= 'localhost:3000'