rspec说自定义路径未定义

时间:2016-07-27 21:00:06

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

我的路线档案中有这个条目

namespace :api do
  namespace :v1 do
    get "/get_info/:pone/:ptwo", to: "whatever#getInfo", as: "get_info"
  end
end

这在我的spec文件中

require 'rails_helper'

RSpec.describe "controller test", type: :request do
  describe "get_info" do
    it "gets info" do
      get get_info_path(55,55)
      expect(response).to have_http_status(200)
    end
  end
end

当我运行我的spec文件时,它会显示undefined local variable or method 'get_info_path'

到目前为止,我发现的所有答案都说将config.include Rails.application.routes.url_helpers添加到spec_helper.rb会解决此问题,但它并没有解决我的问题

这是我的spec_helper:

require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'

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

  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.shared_context_metadata_behavior = :apply_to_host_groups

end

这是我的rails_helper:

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.include Rails.application.routes.url_helpers
  config.include ControllerSpecHelpers, :type => :controller
  config.include FactoryGirl::Syntax::Methods
  config.use_transactional_fixtures = true

  config.infer_spec_type_from_file_location!

  config.filter_rails_from_backtrace!
end

1 个答案:

答案 0 :(得分:1)

如果您运行$ rake routes,您会看到根据配置的路线获得以下输出:

api_v1_get_info GET /api/v1/get_info/:pone/:ptwo(.:format)  api/v1/whatever#getInfo

因此,您需要在规范中使用的路径是api_v1_get_info_path,而不是get_info_path

您的路线

namespace :api do
  namespace :v1 do
    get "/get_info/:pone/:ptwo", to: "whatever#getInfo", as: "get_info"
  end
end

几乎相当于

scope :api, module: :api, as: :api do
  scope :v1, module: :v1, as: :v1 do
    get "/get_info/:pone/:ptwo", to: "whatever#getInfo", as: "get_info"
  end
end

因此,如果您希望使用get_info_path帮助程序以相同的路径路由到同一个控制器,则可以更改路由以删除as选项:

scope :api, module: :api do
  scope :v1, module: :v1 do
    get "/get_info/:pone/:ptwo", to: "whatever#getInfo", as: "get_info"
  end
end

如果你运行$rake routes,那么会给你:

get_info GET /api/v1/get_info/:pone/:ptwo(.:format)  api/v1/whatever#getInfo

有关使用情况scopemodule的详细信息,请查看controller namespaces and routing section of the Rails routing guide