型号: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 []>
看起来[]意味着甚至找不到记录?
任何帮助都会非常感激!
答案 0 :(得分:1)
Rspec的let
语法是懒惰的,这意味着loan
和payment_one
在您的测试中明确调用之前不会存在。由于payment_test
未对loan
或payment_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)
在测试范围内强制加载loan
和payment_one
。