[rspec-users] My very fist spec file (not sure what's wrong..)

Ben Mabey ben at benmabey.com
Mon Jul 20 23:21:28 EDT 2009

Chris Sund wrote:
> Hey Everyone,
> I am finally to the point in the rspec book where it describes how to
> implement controller specs, so I thought what the heck, I'll give it a
> try. I have an app I have been working on (Inside out) that I needed
> to get test specs written for before I continue on with the app. Now
> that I have read enough of the book I realize I was doing things a
> little backwards in the "rspec" sense of BDD, but I thought I would
> try to apply what I have learned so far to my existing code.
> Here's the feedback I'm getting when I run my spec file....
> NoMethodError in 'AccountsController POST create should build a new
> account'
> You have a nil object when you didn't expect it!
> You might have expected an instance of ActiveRecord::Base.
> The error occurred while evaluating nil.save
> /Users/Chris/Rails/obilling/app/controllers/accounts_controller.rb:
> 24:in `create'
> ./spec/controllers/accounts_controller_spec.rb:7:
> script/spec:10:
> Here's my spec file...
> require File.expand_path(File.dirname(__FILE__) + '/../spec_helper' )
> describe AccountsController, "POST create" do
> it "should build a new account"  do
>   Account.should_receive(:new).with("address" => "1201 washington
> street")

This is your problem.. you need to return something for 'save' to be 
called on.  i.e.

  Account.should_receive(:new).with("address" => "1201 washington

Notice the "and_return" at the end?  That way a mock_model of Account will be returned from the new call so that the controller can set it to @account and save it.

To see some examples of RSpec controller specs you can use a generator to general rspec scaffolding... like so:

./script/generate rspec_scaffold Account


More information about the rspec-users mailing list