How can I write a test to assert that the action new
is rendered?
def method
...
render :action => :new
end
I'm looking for something like the lines below, but to assert that the action was called, not the template:
assert_equal layout, @response.layout
assert_equal format, @request.format
I know I can't do @response.action
Thanks in advance!
Deb
For future people that find this, the correct method is:
assert_template :new
Let's say you have a controller action for create, as follows:
def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
format.xml { render :xml => @post, :status => :created, :location => @post }
else
format.html { render :action => "new" }
format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
end
end
end
And here is the standard Scaffold 'posts#new' view
<h1>New post</h1>
<% form_for(@post) do |f| %>
<%= f.error_messages %>
...... # just to show, it's bigger....
Now, if a Post is succesfully created you want to be redirected, but if it fails, we just want to re-render the NEW action. The test below uses what our main man DJTripleThreat said to use assert_template
.
test "should not create post and instead render new" do
post :create, :post => { }
assert_template :new
#added to doubly verify
assert_tag :tag => "h1", :child => /New post/
end
If that still doesn't float your boat, I'd even add an assert_tag to make sure some of the view is coming up, so you know that it is displayed/rendered to the end user.
Hope this helps.
As of Rails 5.0.0, you can test that the action is rendered properly by testing the displayed template.
You first need to add the rails-controller-testing
gem to your Gemfile (as it was extracted outside of Rails since version 5). Then, in your test, simply use:
assert_template :new
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With