Reputation: 8900
When a contract gets created, it takes a Unit, User and Discount and uses those param items (models) to generate an Invoice.
Everything works fine in the browser. But when running a spec, I'm getting undefined method 'value' for nil:NilClass [/app/models/option.rb:19:in 'get_from_database'
Line 18-20 of Option.rb. This is a model for getting site options (configurable by the admin) from the database. Works fine normally (browser tests).
def self.get_from_database(name)
$option[name] = self.find_by_name(name).send('value')
end
And it's being called from Contract.rb:
def start_date=(date)
self[:start_date] = Date.strptime(date, Option.get_from_database('short_date'))
end
Any idea why I'm getting this error? If I comment out this line and re-run the spec test, I get another nil:NilClass
error from another class method call.
I've just started working with rspec, so I'm sure I'm missing something. NOTE: The first test works, the second doesn't.
require 'spec_helper'
module ContractSpecHelper
def contract_params
{ :start_date => "08/09/2012",
:client_id => '1',
:pay_interval_id => '1',
:billing_day => "1",
:prorated => '1',
:require_next => "1",
:include_today => "1",
:unit_id => '45',
:due => "1" }
end
end
describe 'Contract' do
include ContractSpecHelper
before :each do
@contract = Contract.new
end
describe '#new' do
it "requires a unit, user, and pay interval id" do
@contract.should_not be_valid
end
it "creates an invoice once saved" do
@contract.attributes = contract_params
@contract.save
@contract.should have(1).invoice
end
end
end
Upvotes: 0
Views: 85
Reputation: 1281
The issue appears be that Option.find_by_name(name)
is returning nil.
The most likely cause of this is that you're not populating the options table in the test environment. Either change your code to handle Option record not existing, or use fixtures/factory_girl/machinist/ before block (etc) to create option records in your test environment.
(To answer your other question, your environment should be loaded in your spec_helper. You shouldn't need to manually include your rails models into your rspec specs.)
Upvotes: 1