[rspec-users] Unexplainable failure...at least for me

Chris Olsen lists at ruby-forum.com
Wed Nov 7 00:39:00 EST 2007

I have an address model with country_id and province_id fields

There is also a full_address method that returns an address that is in a
format that the google maps api will be able to return a long-lat

Within the full_address method there is a call to obtain the
province/state and country name.
def full_address
  full_address = [city, self.province.name,

When I run this in the console it works fine
>> a = Address.new
=> #<Address:0x24c6420 @new_record=true, @attributes={"city"=>nil,
"latitude"=>nil, "region_code"=>nil, "province_id"=>nil,
"country_id"=>nil, "location_type"=>nil, "location_id"=>nil,
"address_1"=>nil, "address_2"=>nil, "longitude"=>nil, "address_3"=>nil,
>> a.country_id = 1
=> 1
>> a.country.name
=> "Canada"
>> a.province_id = 1
=> 1
>> a.full_address
=> ",,Alberta,Canada"

but when the specs are run I get errors saying that the country and
province object properties are null
NoMethodError in 'Address additional properties should ensure spacing
between the st/ave on the address'
You have a nil object when you didn't expect it!
The error occurred while evaluating nil.name

Here is one of the tests that fail:
describe Address, "additional properties" do

  before(:each) do
    @address = Address.new(valid_params)

  def valid_params
      :country_id => 1,
      :province_id => 1,
      :region_code => "T5Z3J4",
      :address_1 => "13245-56 st",
      :address_2 => "NW",
      :city => "Edmonton"

  it "should return the full address format" do
    @address.country_id.should == 1  #this passes
    @address.province_id.should == 1 #this passes
    @address.province.name.should == "Alberta"  #this fails
    @address.country.name.should == "Canada"   #this fails
    @address.full_address.should == "13245-56 st
NW,Edmonton,Alberta,Canada"  #and this fails if you remove the ones

class Address < ActiveRecord::Base
  belongs_to :province
  belongs_to :country

class Country < ActiveRecord::Base
  has_one :address

If I wasn't able to make it happen in the console, it would make more
sense, but seeing as I can I am totally lost.

Thanks for the help
Posted via http://www.ruby-forum.com/.

More information about the rspec-users mailing list