Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails testing: assert render action

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

like image 542
deb Avatar asked May 26 '10 19:05

deb


3 Answers

For future people that find this, the correct method is:

assert_template :new
like image 194
Mohammad El-Abid Avatar answered Nov 10 '22 17:11

Mohammad El-Abid


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.

like image 9
pjammer Avatar answered Nov 10 '22 15:11

pjammer


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

like image 7
ilovebigmacs Avatar answered Nov 10 '22 15:11

ilovebigmacs