views:

247

answers:

3

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

A: 

Here is a complete list of assertion functions available as a PDF cheat sheet: http://nubyonrails.com/articles/ruby-rails-test-rails-cheat-sheet

I think what you might be interested in is assert_template.

DJTripleThreat
I think you might need an extra gem installed for some of assertions to work: http://github.com/seattlerb/zentest either way this looks like a decent testing suite. (It includes autotest which I like to use)
DJTripleThreat
Thanks for the link to the pdf, but I'm looking for how to assert the action not the template
deb
A: 

The view would be rendered, the action called. Try this:

@controller.expects(:new)
Christian Lescuyer
A: 

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.

pjammer