2011-08-15 74 views
3

最近,我改变了我的控制器代码:测试的Rails 3 respond_with使用RSpec

def create 
    @checklist_item = @checklist.items.build(params[:checklist_item]) 
    if @checklist_item.save 
     flash[:notice] = "Successfully created checklist item." 
     redirect_to checklist_item_url(@checklist, @checklist_item) 
    else 
     render :action => 'new' 
    end 
    end 

respond_to :html, :json 
    def create 
    @checklist_item = @checklist.items.build(params[:checklist_item]) 
    if @checklist_item.save 
     flash[:notice] = "Successfully created checklist item." 
    end 
    respond_with @checklist_item 
    end 

但我的天赋,与我以前的控制器代码工作正常失败:

it "create action should render new template when model is invalid" do 
    checklist_item.stub(:valid? => false) 
    checklist.stub_chain(:items, :build => checklist_item) 
    post :create, :checklist_id => checklist.id 
    response.should render_template(:new) 
    end 

随着错误:

1) Checklists::ItemsController create action should render new template when model is invalid 
    Failure/Error: response.should render_template(:new) 
    MiniTest::Assertion: 
     Expected block to return true value. 

我不知道如何更改规格。当我在浏览器中测试它时,所有功能仍然保持不变(其渲染为新的)。

+0

奇怪它不呈现显示。你确定它会呈现新的? – apneadiving

+0

目标是渲染:新模型是无效的。其他测试通过一个有效的模型可以正常工作并重定向以显示没有问题。 – dMix

回答

1

很有趣,只是试过,确实response不包含太多。

这是一个纯粹的状态302测试:response.status.should eq 302

随着身体像:

"<html><body>You are being <a href=\"new_url">redirected</a>.</body></html>"

这是容易测试过。

我会再挖一点。


编辑:

即使render_viewsresponse仍然是一个单纯的重定向。

你也可以查看response.header它看起来像:

{"Location"=>"http://test.host/users", "Content-Type"=>"text/html; charset=utf-8"} 
+0

是否可以通过身份验证将您重定向到登录页面? – lulalala

1

的原因是,responds_with检查.errors.empty?,而不是valid?(我想这想不不必要的重新运行验证)。所以我推测出来了.errors