简体   繁体   中英

How to test this ==> rspec + rails

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM