【问题标题】:Trouble with namespaced controller spec [duplicate]命名空间控制器规范的问题[重复]
【发布时间】:2019-07-20 12:12:01
【问题描述】:

我有这些 api 路由:

  namespace :api do
    resources :deals, :users
    :airports, only: [:index, :show]
  end

我用rake routes -g airports确认机场路线

      Prefix Verb URI Pattern                 Controller#Action
 api_airports GET  /api/airports(.:format)     api/airports#index
 api_airport GET  /api/airports/:id(.:format) api/airports#show

这是控制器:

class Api::AirportsController < ApplicationController
  def index
    render json: Airport.all
  end

  def show
    @airport = Airport.find(params[:id])
    render json: @airport
  end
end

我可以访问http://localhost:3000/api/airports/2555 并获得我期望的 JSON 响应。

但是,我的规范找不到操作:

describe Api::AirportsController, type: :controller do
  describe "show" do
    it "returns a JSON:API-compliant, serialized object representing the specified Airport" do
      correct_hash = {
        "id" => "2555",
        "type" => "airports",
        "attributes" => {
          "name" => "Ronald Reagan Washington National Airport",
          "city" => "Washington",
          "country" => "United States",
          "iata" => "DCA" 
        },
        "jsonapi" => {
          "version" => "1.0"
        }
      }

      get :show, id: 2555
      returned_json = response.body
      parsed_json = JSON.parse(returned_json)
      expect(parsed_json).to eq correct_hash
    end
  end
end
Failures:

  1) Api::AirportsController show returns a JSON:API-compliant, serialized object representing the specified Airport
     Failure/Error: get :show, id: 2555

     ArgumentError:
       unknown keyword: id
     # ./spec/api/airport_api_spec.rb:18:in `block (3 levels) in <main>'

我在没有id 的情况下尝试过(所以该行只是get :show),但这给出了这个错误:

Failures:

  1) Api::AirportsController show returns a JSON:API-compliant, serialized object representing the specified Airport
     Failure/Error: get :show

     ActionController::UrlGenerationError:
       No route matches {:action=>"show", :controller=>"api/airports"}
     # ./spec/api/airport_api_spec.rb:20:in `block (3 levels) in <main>'

我做错了什么?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    你应该把这个放在params,像这样:

    get :show, params: { id: 2555 }
    

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      • 2020-01-17
      • 2015-04-24
      • 1970-01-01
      相关资源
      最近更新 更多