【问题标题】:Having problem with a nested controller spec with RSpec post rails 5RSpec post rails 5 的嵌套控制器规范有问题
【发布时间】:2020-01-22 18:43:45
【问题描述】:

鉴于这个人为的例子:

RSpec.describe City::Road::HouseController, type: :controller do
  let(:house) { create :house }

  describe 'index' do    
    context 'a request is received without a valid basic-auth header' do
      it 'renders unauthorized' do
        before { method_that_unsets_basic_auth_header }
        get(:index, params: { house_id: house.id })

        expect(response).to have_http_status(:unauthorized)
      end
    end
  end
end

使用以下路线:

namespace :city do
  namespace :road do
    resources :location, only: %i[show index] do
      resources :house, only: %i[index], on: :member
    end
  end
end

为什么我总是收到这个错误?:

 ActionController::UrlGenerationError:
       No route matches {:action=>"index", :controller=>"city/road/house :house_id=>1}

我认为这是因为它忽略了location

我希望路线是:

/city/road/location/:location_id/house

我查看了以下问题/答案,但没有一个有帮助(尽管我承认我可能遗漏了一些东西):

  1. How to test controllers with nested routes using rspec
  2. Rails Rspec controller testing with nested resources
  3. RSpec controller for nested resources, before_action

【问题讨论】:

  • 您希望这条路线究竟是什么?
  • 啊,哎呀,谢谢你的收获!

标签: ruby rspec rspec-rails ruby-on-rails-6


【解决方案1】:

我再次查看了我链接的其他问题/答案,我注意到它们都与我所拥有的不同。

我删除了:member 选项

namespace :city do
  namespace :road do
    resources :location, only: %i[show index] do
      resources :house, only: %i[index]
    end
  end
end

现在规范通过了绿色,我不知道为什么这会影响规​​范,因为无论有没有这个选项,路线看起来都一样。

【讨论】:

  • member 表示希望路由在父作用域的ID作用域内。在这种情况下,这将是一个location_id。因此,您可以像以前那样做,也可以在测试中添加location_id 参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多