2010-05-26 68 views
17

我该如何编写一个测试来声明动作new已被渲染?Rails testing:assert render action

def method 
    ... 
    render :action => :new 
end 

我正在寻找类似下面的台词,但断言,该行动是调用,而不是模板:

assert_equal layout, @response.layout 
assert_equal format, @request.format 

我知道我不能做@response.action

提前致谢!

德布

回答

0

视图将呈现,称为动作。 试试这个:

@controller.expects(:new) 
+0

这个测试的操作方法得到了调用。一个动作可以呈现它选择的任何视图,甚至可以重定向。 – jwadsack 2017-05-05 21:31:30

8

比方说,你有创建一个控制器动作,如下:

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 

这里是标准支架的帖子#新的“视图

<h1>New post</h1> 

<% form_for(@post) do |f| %> 
<%= f.error_messages %> 
...... # just to show, it's bigger.... 

现在,如果邮件成功创建,您希望重定向,但如果失败,我们只想重新呈现NEW操作。以下测试使用我们的主要DJTripleThreat所说的使用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 

如果仍然不浮动你的船,我想即使添加assert_tag以确保某些人看来是来了,让你知道它是显示/呈现给最终用户。

希望这会有所帮助。

70

对于发现这个未来的人,正确的方法是:

assert_template :new 
4

铁轨5.0.0,可以测试该动作是由测试所显示的模板正确地呈现。

您首先需要将rails-controller-testing gem添加到您的Gemfile中(因为它是从版本5以外的Rails之外提取的)。然后,在您的测试,只需使用:

assert_template :new