失败/错误:访问movies_url NameError:未定义的局部变量或方法`movies_url&#39; for#<rspec :: core :: examplegroup :: nested_1:0x007ff450c81800>

时间:2015-06-25 02:35:23

标签: ruby-on-rails ruby rspec tdd capybara

我刚刚开始使用RSpec。我收到错误的是有一个未定义的变量或方法&#39; movies_url&#39;在运行我的spec文件时。这是我运行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这是我正在运行的测试。

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)

1 个答案:

答案 0 :(得分:2)

将其放在spec文件中。

include Rails.application.routes.url_helpers

上面的代码会使你的测试中的所有url助手如root_path,movies_url都可以访问。但是要访问我们也应该在test.rb环境文件中定义主机。以下代码放在test.rb

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