Rspec Gotchas and Integration Mode

This article was published 5 years, 3 months ago. Due to the rapidly evolving nature of web development, some concepts may no longer be applicable.

While trying to spec out a controller with multiple format types, I had trouble getting the right http request invoked. You could always just set the XmlHttpRequest environment variable, but seams hackish to me.
Consider a controller action with multiple request types:


def update
respond_to do |format|
if @object.update_attributes(params[:object])
flash[:notice] = "Object was successfully updated."
format.html { redirect_to object_path @object }
format.json { render :json => {:flash => flash, :object => @object}}
else
flash[:error] = @object.errors.full_messages.to_sentence
format.html { render 'edit' }
format.json { render :json => {:flash => flash, :object => @object }}
end
end
end

With a spec like:


it "should send back json" do
@controller.should_receive(:render).with({:json => {:flash => {:notice=>"Object was successfully updated."}})
xhr :put, :update, {:id => "1"}
end

But it will fail to reach the json format block. You could change it to format.js and the test would pass, but the actual functionality would be borked, because its not json. You have to add a format option to the params, then it won’t matter how you make the http request. Both of the below will work, but the later is more correct:

xhr :put, :update, {:format => "json", :id => "1"}
put, :update, {:format => "json", :id => "1"}

Moral of the story is that xhr is for js not json. Its easy to forget the small things when you use it everyday.

Rspec Integration Mode

While looking through the rspec-rails rdocs the other day, I discovered integration mode. It puts view specs in your controller specs, so it will act more like Test Unit functional tests. I think it could save time, a lot of lines of setup mocking and yield a wider coverage from each spec. I am not a hardcore view spec’er. I mostly only care that the view doesn’t blow up and I let our Selenium integration tests do the rest. I will be trying out rspec integration mode next week and will make sure to let you know what I think.

No Responses to “Rspec Gotchas and Integration Mode”

Comments on this post are closed.