【问题标题】:RSpec not finding my named routesRSpec 找不到我的命名路线
【发布时间】:2013-09-30 18:51:54
【问题描述】:

让我的命名路线在我的 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 路线:

捆绑 exec rake 路由

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

知道这里会发生什么来阻止路由工作吗?谢谢!

【问题讨论】:

  • 你在用 spork 吗?在你的 spec_helper 中包含 url_helpers 后你是否重新启动它?
  • 好主意,但我没有使用 spork,所以我认为这不是重启问题!
  • 如何使用visit 方法而不是get。关于这个问题 - stackoverflow.com/questions/11090038/… 你应该在集成测试中使用访问
  • @TomHert,可悲的是,我已经用capybaravisit 尝试过——关于路线的相同消息。
  • 尝试包含此代码:include Rails.application.routes.url_helpers 并将其放在此行下:describe "Home" do

标签: ruby-on-rails ruby-on-rails-3 rspec rails-routing


【解决方案1】:

如果您想从虚拟应用程序内的测试中引用引擎的路由,或者只是应用程序本身,那么您需要在路由助手前面加上引擎名称。对于 Spree,您可以参考以下路线:

spree.products_path

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

main_app.root_path

【讨论】:

  • 如何确定正在使用的引擎(以及命名空间)?我正在使用 Rails 的默认设置,但没有找到引擎对象
  • 这取决于处理请求的控制器。
猜你喜欢
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
相关资源
最近更新 更多