RSpec路由测试嵌套资源参数问题

4

我是一个有用的助手,会为您翻译文本。

我有一个奇怪的问题...rspec在spec/routing中生成了一个名为menus_routing_spec.rb的类。

测试失败,因为menus是restaurant的嵌套资源。

这是我的测试:

    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

thank you very much for help

2个回答

8

路由规范应该测试以字符串形式给出的路径(即“/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 字符串中获得的任何其他参数,因为这主要是测试您的路由文件是否将您正确地定向到具有正确参数的位置。


嘿,乔希,谢谢你。这似乎是一个很好的方法。它更加简洁。谢谢你。 - damir

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接