简体   繁体   English

在Rails API控制器中测试销毁操作

[英]Testing Destroy Action in Rails API Controller

I'm building a RESTful JSON API with Rails 4.0 and using mongoid as my database. 我正在使用Rails 4.0构建RESTful JSON API,并使用mongoid作为我的数据库。 I'm testing the destroy action for one of my controllers using RSpec. 我正在使用RSpec测试我的一个控制器的销毁动作。 However, when I run my test I receive the ActionController::UrlGenerationError: as Rails is unable to find a corresponding route. 但是,当我运行测试时,我收到ActionController :: UrlGenerationError :,因为Rails无法找到相应的路由。 The weird thing is my destroy action is clearly defined in my routes.rb file and my other controller actions within the same resource work fine. 奇怪的是,我的destroy动作在我的routes.rb文件中已明确定义,并且同一资源内的其他控制器动作也能正常工作。

        describe "DELETE 'delete credit cards'" do
    before do
        @credit = CreditCard.new(cc_last4: Random.rand(1234) ) 
    end

    it "should return a successful json response" do
        params = {comicbook_uid: @user.comicbook_uid.to_s , 
                  notebook_token: @user.comicbook_token, 
                  cc_id: @credit.id, format: :json } 

        delete :destroy, params

        body_hash = JSON.parse response.body

        expect(body_hash["success"]).to eql true
    end

The error that gets generated in my terminal is this: 在我的终端中生成的错误是这样的:

   Failure/Error: delete :destroy, params
   ActionController::UrlGenerationError:

     No route matches {:comicbook_uid=>"52decf924761625bdf000000",  :comicbook_token=>"sfsakjhfk",      
                :cc_id=>BSON::ObjectId('52decf924761625bdf020000'), 
                :format=>:json, :controller=>"credit_cards", 
                :action=>"destroy"}

My routes for the credit card resource look like this: 我的信用卡资源路线如下所示:

 resources :credit_cards, only: [:create, :index, :destroy], 
 :defaults => { :format => 'json'}

Thank you in advance and hope can help me out soon! 预先谢谢您,希望能尽快帮助我!

You aren't passing an id attribute, which is the only param you should actually need. 您没有传递id属性,这是您实际需要的唯一参数。 Moreover, since you are creating your @credit object using CreditCard.new(...) it won't actually have an id until you persist it to the db. 而且,由于您是使用CreditCard.new(...)创建@credit对象的,因此在将其持久保存到数据库之前,它实际上没有ID。

Replace: 更换:

it "should return a successful json response" do
    params = {comicbook_uid: @user.comicbook_uid.to_s , 
              notebook_token: @user.comicbook_token, 
              cc_id: @credit.id, format: :json }

with: 与:

it "should return a successful json response" do
    params = {id: @credit.id, format: :json }

and make sure to persist the CreditCard (or set mock expectations for it to be destroyed). 并确保保留信用卡(或对信用卡被销毁设置模拟的期望)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM