2011-08-15 86 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