Error on nil.build

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

Ooops there was a typo on the method causing the error. It should be:

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

Is there a better way to test that the data is being loaded into the
related models properly?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs