我有一个奇怪的问题.. 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
非常感谢你的帮助
答案 0 :(得分:6)
路由规范应测试给定路径为字符串的操作(get
)(即“/ first / 1 / second / 2”)将路由到具有正确参数集的操作(即{{ 1}})
您无需在此处创建模型实例。这是不必要的,它只会减慢规格。
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
或其他任何可能从URL字符串中收集的参数,因为它主要测试您的路径文件是否使用正确的参数将您引导到正确的位置。 / p>
答案 1 :(得分:0)
好的..我解决了,但我真的不确定这是不是正确的方法..如果有人有不同的方法,请告诉我:)
这对我有用:
it 'routes to #index with correct restaurant id' do
{:get => restaurant_menus_path(@restaurant)}.should route_to(:controller => 'menus', :action => 'index', :restaurant_id => @restaurant.to_param)
end
it 'routes not to #index with wrong restaurant id' do
{:get => restaurant_menus_path(@restaurant)}.should_not route_to(:controller => 'menus', :action => 'index', :restaurant_id => @restaurant1.to_param)
end