开发者

How to test this ==> rspec + rails

开发者 https://www.devze.com 2023-01-17 23:22 出处:网络
We all know that we have this code in our create action of any basic controller def create if @product.save

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开发者_JAVA百科] = "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 :)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消