Model: payment.rb
class Payment < ActiveRecord::Base
belongs_to :loan
def self.previous_payments(id)
where(loan_id: id)
end
end
All I am trying to do is test to make sure a payment is found if it has the correct loan_id
Test:
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
But I keep getting this error:
expected: 1
got: #<ActiveRecord::Relation []>
And it looks like [] means that no records were even found?
Any help at all would be much appreciated!
Rspec's let
syntax is lazy, meaning that loan
and payment_one
won't exist until they are explicitly called in your test. Because payment_test
doesn't make any explicit calls to loan
or payment_one
, it returns an empty relation. If you use let!
, your variables won't be lazily loaded:
let!(:loan) {Loan.create!(id: 1, funded_amount: 1000.0)}
let!(:payment_one) {Payment.create!(amount: 100.0, loan_id: 1)}
You could also do something like
loan.reload
payment_one.reload
expect(payment_test.first.loan_id).to eql(1)
within the test to force loan
and payment_one
to be loaded.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.