views:

28

answers:

2

A contact has_many notes; notes belong_to a contact. In my notes controller, after a successful save of a Note, I redirect to the note's contact using:

format.html { redirect_to(@note.contact, :notice => 'Note was successfully created.') }

In my unit test, I'm testing the ability to create a note and redirect to the note's contact view page. My notes.yml fixture simply sets up the note, and in the setup portion of the notes_controller_test.rb I assign the note from the fixture to @note.

Here's the actual test code:

test "should create note" do
  assert_difference('Note.count') do
    post :create, :note => @note.attributes
  end
end

I think the note is successfully saving, but the redirect is failing. So it looks like the redirect_to in the controller is throwing up the "Cannot redirect to nil!" error, but I can't seem to understand why.

Here is my Notes create action:

def create
@note = Note.new(params[:note])

respond_to do |format|
  if @note.save
    format.html { redirect_to(@note.contact, :notice => 'Note was successfully created.') }
    format.xml  { render :xml => @note.contact, :status => :created, :location => @note.contact }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @note.contact.errors, :status => :unprocessable_entity }
  end
end

end

+1  A: 

It would appear that your fixture is not creating and/or loading the contact on @note. The 'redirect to nil' is thrown because @note.contact is returning nil. Make sure that your note's contact_id is valid and that note is loaded from the db with its contact before the test runs.

Dave Sims
Steve
Oh! In my contact fixture, I'm not declaring an ID. It's simply first and last name. So the test is actually giving it a crazy ID that doesn't correspond with the contact_id field in my note fixture.
Steve
Fixtures can be a pain that way. Check out Machinist or FactoryGirl for a better approach. I've used both a good bit, I prefer Machinist. Take an hour and learn it. Totally worth your while. http://github.com/notahat/machinist
Dave Sims
A: 

When I was adding my contact fixtures, I didn't specify an ID when declaring values. I simply put:

one:
  firstname: John
  lastname: doe

I've added an id field to the fixture and the test passes. Sweet! :) Thanks for pointing me in the right direction. It looks as if you don't specify a specific ID, then it'll give it a crazy long random ID (seen in test.log).

Is there a way to give it an ID that will connect it with note fixture without hardcoding a number there?

one:
  firstname: John
  lastname: doe

And then in my notes fixture:

one:
  body: This is a note text.
  contact_id: <%= contacts(:one).id %>

Would that work?

Steve