开发者

Rails testing: assert render action

开发者 https://www.devze.com 2023-01-01 17:36 出处:网络
How can I write a test to assert that the action new is rendered? def method ... render :action => :new

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 temp开发者_开发知识库late:

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


My original answer is wrong. As @Mohammad El-Abid indicated below, the correct method is:

assert_template :new

Original answer:

The view would be rendered, the action called. Try this: @controller.expects(:new)

0

精彩评论

暂无评论...
验证码 换一张
取 消