Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails respond_with & Rspec controllers: Testing unsuccessful update

I'm trying to switch from using respond_to to respond_with in Rails controllers. Everything's going smoothly, except for testing invalid saves in controller specs. Here's an example:

describe MyController do ...

describe "PUT update" do
    context "with invalid attributes" do
      it "should re-render the edit page" do
        style = stub_model(Style)
        Style.stub(:find) { style } 
        Style.any_instance.stub(:save).and_return(false)
        put :update
        response.should render_template(:edit)
      end
    end
  end
end

This works just fine with my old respond_to style update action, but with respond_with, I get

Failure/Error: response.should render_template("edit")

So, in short - how do I test this? ...Or should I just assume render_with knows what it's doing and not test at all? Any general suggestions?

Cheers in advance

PS: The update action:

  def update
    @style = Style.find(params[:id])
    flash[:notice] = "Style updated" if @style.update_attributes(params[:style])
    respond_with(@style)
  end
like image 950
PlankTon Avatar asked Apr 18 '12 17:04

PlankTon


1 Answers

I've been looking into this exact thing (how I found this topic) - so far I have the following:

Location.any_instance.stub(:valid?).and_return(false)
Location.any_instance.stub(:errors).and_return('anything')

(where Location is my model that uses respond_with)

however I believe there must be a nicer way to do it - if I find it, I'll be sure to post it!

Note: I'm also using the responders gem so one of these lines may not be necessary for you if you're not using it!

like image 102
sevenseacat Avatar answered Sep 22 '22 04:09

sevenseacat