[rspec-users] lots of nil problems!

Nick Hoffman lists at ruby-forum.com
Sat Mar 20 00:55:39 EDT 2010


Hey Patrick.

> I have this in my controller action:
> 
> from_address = Setting.find_by_name("shipping_from_address").address
> 
> and my spec fails:
> 
> NoMethodError in 'Admin::ShippingLabelsController should render a pdf
> file'
> undefined method `address' for nil:NilClass
> 
> yet in the console I can do:
> 
>>>  Setting.find_by_name("shipping_from_address").address
> 
> => #<Address id: 1970, label: .... etc>
> 
> and I get the address-- so I don't understand why it's failing in the
> spec.. ?

Your console was most likely running in the development environment, and 
thus using your development database. Specs run in the test environment, 
and use your test database. Thus, your specs won't see the data in your 
dev DB.

Also, your test DB is wiped clean at the beginning of all of your tests. 
That way, existing data can't taint or skew the results of your specs.

You probably want something along the lines of this:
http://pastie.org/878189

However, that line of code of yours should be modified slightly. At the 
moment, it'll raise the error that you posted above if the setting isn't 
found. This is because Setting.find_by_name returns nil if the setting 
isn't found, and nil#address doesn't exist.

You can put Object#try right before the call to #address, like this:
  Setting.find_by_name('...').try(:address)
I'd probably break the line into a few: search for the setting, then 
check if it's nil, then grab the address or deal with the nil value.

There're many solutions. Try a few and see what feels right to you.
-- 
Posted via http://www.ruby-forum.com/.


More information about the rspec-users mailing list