我需要帮助在 rails 中编写 rspec 测试

I need help to write the rspec test in rails

我有一个items_controller.rb

  def get_serialized_copy_of_item
    @item= Item.find_by_id(params[:id]) 
    if @item.nil?
      head :no_content
    else
      respond_to do |format|
      serialized_item = @item.as_json(include: [:test1, :test2, :test3, :test4])
      format.html
      format.json { render json: serialized_item }  
      end
    end
  end

routes.rb

namespace :items do
  get '/get_serialized_copy_of_item/:id', to:'items#get_serialized_copy_of_item'
end

我想写一个rspec测试

  1. 提交错误的商品 ID 并确保返回 204

我完成了

require 'spec_helper'

describe Items::ItemsController do
  describe "GET items#get_serialized_copy_of_item" do
     it "renders 204 status code" do
      get "/items/get_serialized_copy_of_item/dfsdf"
      expect(last_response.status).to eq(204)
    end
  end
end

错误:我收到路由错误

F

Failures:

  1) Items::ItemsController GET items#item renders 204 status code
     Failure/Error: get "/items/get_serialized_copy_of_item/dfsdf"
     ActionController::RoutingError:
       No route matches {:controller=>"items/items", :action=>"/items/get_serialized_copy_of_item/dfsdf"}
     # ./spec/controllers/items/items_controller_spec.rb:6:in `block (3 levels) in <top (required)>'

Finished in 0.01576 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/controllers/items/items_controller_spec.rb:5 # Items::itemsController GET items#item renders 204 status code

捆绑执行耙路由

                                       GET    `items/get_serialized_copy_of_item/:id(.:format)                            items/items#get_serialized_copy_of_item`

谢谢

RSpec 从测试名称中假定控制器名称。请注意 this doc 中的示例:

describe WidgetsController do
  describe "GET index" do
    it "has a 200 status code" do
      get :index
      response.code.should eq("200")
    end
  end
end

这里RSpec因为describe WidgetsController已经知道路径的widgets部分,所以get方法只接受:index作为参数。

将其转化为您的情况:

describe Items::ItemsController do
  describe "GET get_serialized_copy_of_item" do
     it "renders 204 status code" do
      get :get_serialized_copy_of_item, id: 'sdf'

      expect(response.status).to eq(204)
    end
  end
end
  1. 您只需要将动作的名称传递给get()方法,而不是整个路径。
  2. 您需要包含 :id 参数作为 get()
  3. 的第二个参数
  4. 似乎namespace 是这里进行路由的错误方法。尝试将您的路由定义更改为:
resources :items do 
  member do 
    get :get_serialized_copy
  end
end

这将生成以下路由:

➜  bundle exec rake routes
   Prefix Verb   URI Pattern     

    Controller#Action
get_serialized_copy_item GET    /items/:id/get_serialized_copy(.:format) items#get_serialized_copy

为此,您希望 ItemsControllerapp/controllers/items_controller.rb

据我所知,没有任何嵌套。

如果是这样,您应该调用 ItemsController 而不是 Items::ItemsController

items_controller_spec:

require 'spec_helper'

describe ItemsController do
  describe "GET #get_serialized_copy_of_item" do
     it "renders 204 status code" do
      get "/items/get_serialized_copy_of_item/dfsdf"
      expect(last_response.status).to eq(204)
    end
  end
end