簡體   English   中英

如何測試此==> rspec + rails

[英]How to test this ==> rspec + rails

我們都知道在任何基本控制器的create動作中都有此代碼

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

我們如何使用rspec測試這部分代碼

任何建議都是最歡迎的。

PS:我對rspec天真,所以請介意我問這個問題,如果答案很簡單:)

非凡的Rails gem為rspec添加了一些匹配器,可用於測試通知,重定向和&c。 這個(未經測試的)product_controller_spec.rb顯示了如何使用非凡的_rails匹配器來測試您的代碼片段:

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

出色的軌道提供了上面使用的render_template,set_the_flash和redirect_to匹配器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM