ruby-on-rails – RSpec路由测试嵌套资源中的参数问题
发布时间:2020-12-17 03:06:31 所属栏目:百科 来源:网络整理
导读:我有一个奇怪的问题.. rspec在spec / routing中生成了一个名为menus_routing_spec.rb的类 测试失败,因为菜单是餐馆的嵌套资源. 这是我的测试: describe MenusController do before :each do @restaurant = FactoryGirl.create(:random_restaurant) @menu =
我有一个奇怪的问题.. rspec在spec / routing中生成了一个名为menus_routing_spec.rb的类
测试失败,因为菜单是餐馆的嵌套资源. 这是我的测试: describe MenusController do before :each do @restaurant = FactoryGirl.create(:random_restaurant) @menu = FactoryGirl.create(:menu) end describe 'routing' do it 'routes to #index' do params = {} params['restaurant_id'] = @restaurant #get('/restaurants/:restaurant_id/menus').should route_to('menus#index') #get(restaurant_menus_path(@restaurant)).should route_to('menus#index') #get(restaurant_menus_path,{ :restaurant_id => @restaurant }).should route_to('menus#index') get restaurant_menus_path,{ :restaurant_id => @restaurant.to_param } expect(response).should route_to('menus#index') end rake路由中的路径如下所示: restaurant_menus_path GET (/:locale)/restaurants/:restaurant_id/menus(.:format) menus#index 我总是收到此错误消息: Failure/Error: get restaurant_menus_path,@restaurant.to_param ActionController::UrlGenerationError: No route matches {:action=>"index",:controller=>"menus"} missing required keys: [:restaurant_id] 我也尝试了其他的..但同样的错误.. 这是spec / controllers / menus_controller_spec.rb中的测试,它可以正常工作 it 'renders the index template' do get :index,{ :restaurant_id => @restaurant } expect(response).to render_template('index') end 非常感谢你的帮助 解决方法
路由规范应该测试给定路径作为字符串的动作(get)(即“/ first / 1 / second / 2”)将路由到具有正确参数集的动作(即first_id:1,id:2)
您无需在此处创建模型实例.这是不必要的,它只会减慢规格. describe MenusController do describe 'routing' do it 'routes to #index' do get('/restaurants/42/menus').should route_to('menus#index',restaurant_id: 42) end it 'routes to #show' do get('/restaurants/42/menus/37').should route_to('menus#index',restaurant_id: 42,id: 37) end end end 您还可以传入其他参数,例如format :: json,或者可能从URL字符串中收集的任何其他参数,因为它主要测试您的routes文件使用正确的参数将您引导到正确的位置. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |