Testing Rails 3 response_with with RSpec

I recently changed my controller code:

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 

to

  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 

But my specification, which did a great job with my previous controller code, fails:

  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 

With an error:

 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. 

I am not sure how to change the specification. Everything remains the same when I test it in a browser (a new one renders it).

+4
source share
2 answers

Pretty funny, just tried it and really response does not contain much.

This is simply status 302. Test: response.status.should eq 302

With a body like:

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

which is easy to verify.

I will dig a little further.


Edit:

Even with render_views , response remains a simple redirect.

You can also check response.header , which looks like this:

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

.errors.empty? reason that responses_with checks .errors.empty? unlike valid? (I suppose he does not want to unnecessarily re-run checks). So cut .errors , I think.

+1
source

All Articles