Testing Rails 3 respond_with with RSpec
I recently changed my controller code from:
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, @ch开发者_运维百科ecklist_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 spec that worked fine with my previous controller code is failing:
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 the 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'm not sure how to change the spec. Everything still functions the same when I test it in the browser (its renders new).
Pretty funny, just tried and indeed the response
doesn't contain much.
It's a mere 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 easily testable too.
I'll dig a little further.
Edit:
Even with render_views
, response
remains a mere redirect.
You could also check response.header
which looks like:
{"Location"=>"http://test.host/users", "Content-Type"=>"text/html; charset=utf-8"}
The reason is that responds_with checks .errors.empty?
as opposed to valid?
(I suppose it doesn't want to unnecessarily re-run validations). So stub out .errors
I guess.
精彩评论