我有一个简单的模型,其中付款属于贷款。我正在使用rspec和shoulda-matcher来测试验证。但是我一直收到指向未完成余额的错误 - 表明它是nil类的未定义方法。但是当我在rails控制台中使用模型时,这个验证工作正常。任何人都知道为什么它没有通过测试???
感谢。
class Payment < ActiveRecord::Base
belongs_to :loan
validates_presence_of :loan_id
validate :proper_amount
private
def proper_amount
errors.add(:amount, "proper") if amount > loan.outstanding_balance
end
end
FactoryGirl.define do
factory :payment do
loan
amount 100.0
post_at Date.today
end
end
FactoryGirl.define do
factory :loan do
funded_amount 5000.0
end
end
RSpec.describe Payment do
before (:all) do
@loan = FactoryGirl.create(:loan)
@payment = FactoryGirl.create(:payment, loan: @loan)
end
describe 'ActiveModel validations' do
#basic validations on attributes
it { should validate_presence_of(:loan_id) }
end
end
Failure/Error: it { should validate_presence_of(:amount) }
NoMethodError:
undefined method `outstanding_balance' for nil:NilClass
答案 0 :(得分:0)
是否匹配器使用您未设置的主题。据我了解,RSpec将初始化一个。
RSpec.describe Payment do
let!(:loan){ FactoryGirl.create(:loan) }
subject!(:payment){ FactoryGirl.create(:payment, loan: loan) }
describe 'ActiveModel validations' do
#basic validations on attributes
it { should validate_presence_of(:loan_id) }
end
end
现在,您不需要使用@loan和@payment,而是需要在其他测试中使用贷款和付款。