【问题标题】:RSpec routing test problems with params in nested resourcesRSpec路由测试问题与嵌套资源中的参数
【发布时间】:2014-02-04 10:51:22
【问题描述】:

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

测试失败是因为 menus 是餐厅的嵌套资源。

这是我的测试:

    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

非常感谢您的帮助

【问题讨论】:

    标签: ruby-on-rails ruby rspec param nested-resources


    【解决方案1】:

    路由规范应该测试给定路径作为字符串(即“/first/1/second/2”)的操作(get)将路由到具有正确参数集的操作(即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 字符串中收集到的参数,因为它主要测试您的路由文件是否使用正确的参数将您引导到正确的位置。

    【讨论】:

    • 嘿乔希,谢谢你..这似乎是一个很好的方法..它更干净..谢谢..
    【解决方案2】:

    好的..我解决了,但我真的不确定这是否是正确的方法..如果有人有不同的方法,请告诉我:)

    这对我有用:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-18
      相关资源
      最近更新 更多