2016-04-03 22 views
0

コントローラー:payments_controller.rbRSpecのテストJSONポストRailsのための

class PaymentsController < ApplicationController 

    # This is needed to have Postman work 
    skip_before_action :verify_authenticity_token 

    rescue_from ActiveRecord::RecordNotFound do |exception| 
    render json: 'not_found', status: :not_found 

    def create 
    new_payment = Payment.new(new_params) 
    current_loan = Loan.find(new_params[:loan_id]) 

    if Payment.valid?(new_payment, current_loan) 
     Payment.received(new_payment, current_loan) 
     current_loan.save 
     new_payment.save 
     redirect_to '/loans' 
    else 
     raise 'Amount entered is above the remaining balance' 
    end 
    end  

end 

私はポストマンでそれをテストする場合、このメソッドは動作します。しかし、私はそれを渡すためのテストを書くように見えることはできません。私は現在持っている:

payments_controller_spec.rb

require 'rails_helper' 

RSpec.describe PaymentsController, type: :controller do 

    describe "#create", :type => :request do 
    let!(:loan) {Loan.create!(id: 1, funded_amount: 500.0)} 
    params = '{"payment":{"amount":400, "loan_id":2}}' 

    it 'creates and saves a payment while saving the associated fund_amount of the loan' do 
     post "/payments", params.to_json, {'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json'} 
     expect(loan.funded_amount).to eql(600.0) 
    end 
    end 
end 

にエラーがある:

Failure/Error: post "/payments", params.to_json, {'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json'} 
ActionController::ParameterMissing: 
    param is missing or the value is empty: payment 

有効なパラメータ(ポストマンとその仕事は)次のとおりです。

{"payment":{"amount":400,"loan_id":2}} 

すべてのヘルプは次のようになり感謝!

*** UPDATE ****

しばらくの間、このいじりの後、私は最終的にはこれで動作するようになったが:

describe "#create", :type => :request do 
    let!(:loan) {Loan.create!(id: 1, funded_amount: 500.0)} 

    it 'creates and saves a payment while saving the associated fund_amount of the loan' do 
    json = { :format => 'json', :payment => { :amount => 200.0, :loan_id => 1 } } 
    post '/payments', json 
    loan.reload 
    expect(loan.funded_amount).to eql(300.0) 
    end 
end 
+0

'current_loan = Loan.find(new_params [:loan_id])? Payment.valid(new_payment、current_loan)' イムはちょうどuはオブジェクト全体を渡すか疑問場合は? – 7urkm3n

答えて

0

あなたはこのようなあなたのparamsに渡すことができます。

it 'creates and saves a payment while saving the associated fund_amount of the loan' do 
    post "/payments", payment: { amount: 400, loan_id: 1 }, {'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json'} 
    expect(loan.funded_amount).to eql(600.0) 
end 
+0

ありがとうアンソニー。私はそれがお金を好きだとは思わない:{金額:400、loan_id:1}引用符ではありません。 Desktop/payments_challenge/spec/controllers/payments_controller_spec.rb:10:構文エラー、予期しない '\ n'、予想=>(SyntaxError) – user3007294

+0

あなたはこれを試すことができますか? '{payment:{amount:400、loan_id:1}}' –

+0

まだ動作しません:/ – user3007294

関連する問題