RSpec找不到我的命名路由

5
我很难理解为什么我的命名路由无法在rspec测试中正常工作。
以下是我所看到的情况:
1) Home GET / works!
 Failure/Error: get root_path
 NameError:
   undefined local variable or method `root_path' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x007fe13b0c1538>
 # ./spec/requests/home_spec.rb:6:in `block (3 levels) in <top (required)>'

2) Home GET / shows products!
 Failure/Error: get products_path
 NameError:
   undefined local variable or method `products_path' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x007fe13b0cdea0>
 # ./spec/requests/home_spec.rb:10:in `block (3 levels) in <top (required)>'

spec/requests/home_spec.rb

require 'spec_helper'

describe "Home" do
  describe "GET /" do
    it "works!" do
      get root_path
      response.status.should be(200)
    end
    it "shows products!" do
      get products_path
      response.status.should be(200)
    end
  end  
end

spec/spec_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

require 'spree/core/testing_support/factories'

RSpec.configure do |config|
  config.mock_with :rspec
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_base_class_for_anonymous_controllers = false
  config.before(:suite) do
    # DatabaseCleaner.strategy = :truncation
  end
  config.before(:each) do
    # DatabaseCleaner.start
  end
  config.after(:each) do
    # DatabaseCleaner.clean
  end

  config.include Rails.application.routes.url_helpers
end

您可以看到测试包含spec_helper,而spec_helper包含路由方法。这是我的rake routes:

bundle exec rake routes

...
             root        /                        spree/home#index
         products GET    /products(.:format)      spree/products#index
...

有任何想法是什么原因导致路由无法工作吗?谢谢!

你正在使用 Spork 吗?在将 url_helpers 加入 spec_helper 后,你是否重启了它? - usha
好的想法,但我没有使用 spork,所以我不认为这是一个重启问题! - isthmuses
使用visit方法代替get方法怎么样?关于这个问题 - https://dev59.com/RmXWa4cB1Zd3GeqPJx4W 在集成测试中应该使用visit方法。 - Tom Hert
@TomHert,不幸的是我已经尝试使用capybaravisit了——关于路由的消息也是一样的。 - isthmuses
请尝试将以下代码包含进来:include Rails.application.routes.url_helpers,并将其放在这行下面:describe "Home" do - Tom Hert
1个回答

7
如果您希望在虚拟应用程序内的测试中引用引擎的路由,或者只是应用程序本身,则需要在路由助手前缀中添加引擎名称。对于Spree,您将引用以下路由:
spree.products_path

同样地,如果你想从引擎中引用主应用程序的路由,你需要使用 main_app

main_app.root_path

如何确定正在使用哪个引擎(因此是哪个命名空间)?我正在使用Rails默认的任何内容,但无法找到引擎对象。 - Jeff
这取决于处理请求的控制器。 - Ryan Bigg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接