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, :locati开发者_StackOverflow中文版on => @note.contact }
else
format.html { render :action => "new" }
format.xml { render :xml => @note.contact.errors, :status => :unprocessable_entity }
end
end
end
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.
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?
精彩评论