无法使模型通过ActiveRecord关系传递Rspec

时间:2016-04-03 18:30:21

标签: ruby-on-rails rspec

型号:payment.rb

class Payment < ActiveRecord::Base
  belongs_to :loan

  def self.previous_payments(id)
    where(loan_id: id)
  end

end

我要做的就是测试以确保如果有正确的loan_id付款

测试:

describe '#self.previous_payments' do
  let(:loan) {Loan.create!(id: 1, funded_amount: 1000.0)}
  let(:payment_one) {Payment.create!(amount: 100.0, loan_id: 1)}
  let(:payment_test) {Payment.previous_payments(1)}

  it 'retrieves all the payments made for a specific loan' do
    expect(payment_test.first.loan_id).to eql(1)
  end
end

但我一直收到这个错误:

expected: 1
got: #<ActiveRecord::Relation []>

看起来[]意味着甚至找不到记录?

任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:1)

Rspec的let语法是懒惰的,这意味着loanpayment_one在您的测试中明确调用之前不会存在。由于payment_test未对loanpayment_one进行任何显式调用,因此会返回空关系。如果您使用let!,则不会延迟加载变量:

let!(:loan) {Loan.create!(id: 1, funded_amount: 1000.0)}
let!(:payment_one) {Payment.create!(amount: 100.0, loan_id: 1)}

您也可以执行类似

的操作
loan.reload
payment_one.reload
expect(payment_test.first.loan_id).to eql(1)

在测试范围内强制加载loanpayment_one