2016-04-03 57 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)' 我只是想知道如何ü传递整个对象? – 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

谢谢安东尼。我不认为它喜欢付款:{amount:400,loan_id:1}不在引号中。我得到这个错误:桌面/ payments_challenge /规格/控制器/ payments_controller_spec.rb:10:语法错误,意外的'\ n',期待=>(SyntaxError) – user3007294

+0

嗯,你可以试试吗? '{payment:{amount:400,loan_id:1}}' –

+0

仍然无效:/ – user3007294