views:

59

answers:

1

We all know that we have this code in our create action of any basic controller

def create
    if @product.save
      flash[:notice] = 'Product was successfully created.' 
      redirect_to(products_path)
    else
      flash[:notice] = "Data not saved try again"
      render :action => "new"
    end
end

how do we test this part of code using rspec

Any suggesstions are most welcome.

P.S I am naive at rspec so please mind me asking this question if the answer to this is damn simple :)

+2  A: 

The remarkable-rails gem adds some matchers to rspec that you can use to test notices, redirects, and &c. This (untested) product_controller_spec.rb shows how you might use remarkable_rails matchers to test your code snippet:

describe ProductController do

  describe "create" do

    before(:each) do
      @product = products(:window_cleaner)
    end

    it "should create a product" do
      @product.should_receive(:save).and_return(true)
      post :create
      should set_the_flash :notice,
                           :to => 'Production was successfully created.'
      should redirect_to products_path
    end

    it "should handle failure to create a product" do
      @product.should_receive(:save).and_return(false)
      post :create
      should set_the_flash :notice, :to => 'Data not saved try again.'
      should render_template :action => 'new'
    end

  end

end

Remarkable-rails provided the render_template, set_the_flash, and redirect_to matchers used above.

Wayne Conrad
@Wayne can we use the should_receive(:save) method by barely using rspec or is it necessary to use the gem
Rohit
@Rohit, You can use rspec alone to mock the call to Product.save. That part is plain old rspec.
Wayne Conrad
@Wayne I did not use the plugin you recommended instead I used this http://www.slideshare.net/fnando/testando-rails-apps-com-rspec to test the particular routine. But still I have a feeling that your way might be right. So I am giving an upvote.
Rohit
@Rohit, Thank you for the vote and the link. Rspec will work well for you, I'm sure. Remarkable-rails is just a gem that adds some new matchers to rspec. You can use rspec just fine without it.
Wayne Conrad