在rspec文件中,我得到=>错误:ActionController :: RoutingError:尽管路由有效,但没有路由与xxxxxxx匹配

问题描述 投票:0回答:1

我对测试非常陌生,对Rails还是很陌生(不到1年的经验)。在回答之前,请注意这一点。

我有一个模型recipe属于sourcesource属于client

路线是:

client_source_recipes GET /clients/:client_id/sources/:source_id/recipes(.:format) recipes#index

我正在尝试对此进行测试:

RSpec.describe RecipesController, :type => :controller do

# Prerequisites go here (mentioned at the end of the question)

  describe "GET #index" do
    it "assigns all recipes as @recipes" do
      recipe = Recipe.create! valid_attributes
      get :index, params: { client_id: client.id, source_id: source.id, locale: 'cs' }, session: valid_session
      expect(assigns(:recipes)).to eq([recipe])

      # Commented below are different ways I tried but failed:

      # visit client_source_recipes_path(client.id, source.id, locale: 'cs')
      # visit "/client/#{client.id}/source/#{source.id}/recipes?locale=cs"
      # get client_source_recipes_path, params: { client_id: client.id, source_id: source.id, locale: 'cs' }, session: valid_session
      # get client_source_recipes_path(client.id, source.id, locale: 'cs')
    end
  end
end

测试先决条件:

  login_user         # defined - works well

  let(:client) { create :client }                                         # defined in factories 
  let(:source) { create :source, warehouse_id: 1, client_id: client.id }  # defined in factories

  let(:valid_attributes) {
    { name: "name", source_id: source.id }
  }

  let(:valid_session) { {"warden.user.user.key" => session["warden.user.user.key"]} }   # works well in other tests

为什么在其他地方都使用相同的路由时为什么会出现路由错误?

错误:

 Error: ActionController::RoutingError: No route matches {:controller=>"recipes", :params=>{:client_id=>"1", :source_id=>"1", :locale=>"cs"}, :session=>{"warden.user.user.key"=>[["1"], "$2a$04$bobnhLAlKEsxZtlJheY64."]}}

 Error: ActionController::RoutingError: No route matches {:controller=>"recipes", :action=>"/clients/1/sources/1/recipes?locale=cs"}

 Error: ActionController::RoutingError: No route matches {:controller=>"recipes", :action=>"/clients/1/sources/1/recipes"}

# etc. etc. i.e. errors are more or less the same

提前感谢。

ruby-on-rails testing routing rspec-rails
1个回答
0
投票

确定!

[我花了5个小时来思考这个问题,但是以任何方式都做不到,现在我发现唯一的问题是语法:

错误的(旧的)语法(明确地将参数和会话作为参数):

get :index, { client_id: client.id, source_id: source.id, locale: 'cs' }, session: valid_session

#or

get :index, params: { client_id: client.id, source_id: source.id, locale: 'cs' }, session: valid_session

右(较新的)语法(隐式接受参数和会话作为参数):

get :index, { client_id: client.id, source_id: source.id, locale: 'cs' }, valid_session

我希望它可以节省其他人的宝贵时间,与我不同):

© www.soinside.com 2019 - 2024. All rights reserved.