[rspec-users] Error on nil.build

Chris Olsen lists at ruby-forum.com
Mon Feb 4 17:24:38 EST 2008


I can't figure out why I am getting an error for one of the tests below:
========================
describe AccountsController, "POST" do
  before :each do
    @user = mock_model(User)
    @account = mock_model(Account, :id => 1, :valid => true, :save =>
true, :users => mock("users", :build => @user))
    Account.should_receive(:new).and_return(@account)
  end

  def do_post
    post "create", {:account => {}, :user => {}}
  end

  it "should make the relation to the users" do
    @account.should_receive(:users).and_return
    do_post
  end

  #this test passes
  it "should receive the save method call" do
    @account.should_receive(:save).and_return(true)
    do_post
  end
end
========================
#Controller code
  def create
    @account = Account.new(params[:account])
    @user = @account.users.build(params[:user])

    if @account.save
      #log the user in to allow them to be directed to their control
panel
      self.current_user = User.authenticate(params[:user][:login],
params[:user][:password])
      redirect_to admin_account_url(@account)
    else
      render :action => "new"
    end
  end
========================

It is this test that fails
it "should make the relation to the users" do
  @account.should_receive(:users).and_return
  do_post
end

with the following error:
========================
NoMethodError in 'AccountsController POST should make the relation to
the users'
You have a nil object when you didn't expect it!
The error occurred while evaluating nil.build

I thought that:
@account = mock_model(Account, ..., :users => mock("users", :build =>
@user))
would allow the call to users to stubbed out and pass the test.

What is it that I am missing?

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


More information about the rspec-users mailing list