ActionController :: UnknownFormat:使用Rspec时

时间:2014-04-25 12:55:16

标签: ruby-on-rails ruby rspec actioncontroller

我正在创建一个简单的API来对联系人执行CRUD操作。 :index:show:create:update方法正常运行,它们都通过各自的请求rspec测试。问题只出现在:destroy方法中。 :destroy操作如下所示:

class Api::V1::ContactsController < ApplicationController

  def destroy
    @contact = Contact.find(params[:id])
    @contact.destroy

    respond_to do |format|
      format.json {render action: :index }
    end
  end
end 

测试DELETE请求的规范如下所示:

 describe "DELETE /api/v1/contacts/:id" do
  before(:each) do
   @contact = FactoryGirl.create(:contact)
  end

  it "it should have a status code of 200" do
    delete "/api/v1/contacts/#{@contact.id}"
    expect(response.status).to eq(200)
  end

  it "It should delete a contact" do
    expect{
      delete "/api/v1/contacts/#{@contact.id}"
    }.to change(Contact, :count).by(-1)
  end
end

当我运行测试时,我收到此错误消息:

Failure/Error: delete "/api/v1/contacts/#{@contact.id}"
 ActionController::UnknownFormat:
   ActionController::UnknownFormat
# ./app/controllers/api/v1/contacts_controller.rb:67:in `destroy'

respond_to do |format|contacts_controller.rb

中的第67行

1 个答案:

答案 0 :(得分:1)

尝试将请求的格式更改为JSON,即替换

delete "/api/v1/contacts/#{@contact.id}"

通过

delete "/api/v1/contacts/#{@contact.id}.json"

允许format逻辑确定你想要用它知道的JSON呈现的回复。