【问题标题】:Testing Destroy Action in Rails API Controller在 Rails API 控制器中测试销毁操作
【发布时间】:2014-01-21 20:14:31
【问题描述】:

我正在使用 Rails 4.0 构建一个 RESTful JSON API,并使用 mongoid 作为我的数据库。我正在使用 RSpec 测试我的一个控制器的销毁操作。但是,当我运行测试时,我收到 ActionController::UrlGenerationError: 因为 Rails 无法找到相应的路线。奇怪的是我的销毁操作在我的 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

在我的终端中生成的错误是这样的:

   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"}

我的信用卡资源路径如下所示:

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

提前谢谢你,希望能尽快帮助我!

【问题讨论】:

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


    【解决方案1】:

    您没有传递id 属性,这是您实际需要的唯一参数。此外,由于您正在使用 CreditCard.new(...) 创建您的 @credit 对象,因此在将其持久化到数据库之前它实际上不会有一个 id。

    替换:

    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 }
    

    与:

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

    并确保保留 CreditCard(或设置要销毁的模拟预期)。

    【讨论】:

    • 在哪里需要传递id属性?查看我的控制器规范,我在文件顶部有一个创建用户的 before 块。因此,这里的 before 块是没有根据的。我知道我需要传递 id 属性,但我不知道在哪里传递它。感谢您的帮助。
    • 您是在破坏用户还是信用卡?看来您需要先创建一张信用卡,然后再尝试销毁它...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多