0

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 :)

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

can we use the should_receive(:save) method by barely using rspec or is it necessary to use the gem
@Rohit, You can use rspec alone to mock the call to Product.save. That part is plain old rspec.
I did not use the plugin you recommended instead I used this 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, 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.