2016-07-27 30 views
1

我有這個條目我的路線文件rspec的說,自定義路徑是不確定的

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

,這在我的規格文件

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 

當我跑我的規格文件,它說:undefined local variable or method 'get_info_path'

到目前爲止我發現的所有答案都表明,向spec_helper.rb添加config.include Rails.application.routes.url_helpers將解決此問題,但它不能解決我的問題

這裏是我的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 
+0

您是否已將'config.include Rails.application.routes.url_helpers'添加到'RSpec.configure do | config |'塊中? –

+0

那會是肯定的 – Jarfis

+0

你的spec_helper.rb是什麼樣的? –

回答

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 

W高血壓腦出血,如果您運行$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

+0

就是這樣,謝謝。我不知道命名空間也改變了自定義路線的命名 – Jarfis