2010-09-27 38 views
0

我們都知道,我們在任何基本控制器如何測試這個==> rspec的軌道+

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的天真,所以請介意我問這個問題,如果這個問題的答案是簡單的該死:)

回答

2

remarkable-rails gem增加了一些匹配器來,你可以使用測試通知,重定向rspec的,和& c。這(未經測試)product_controller_spec.rb說明了如何使用remarkable_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的上面使用的匹配。

+0

我們可以通過幾乎不使用rspec來使用should_receive(:save)方法,或者需要使用gem – Rohit 2010-09-27 14:36:04

+0

@Rohit,您可以單獨使用rspec來模擬對Product.save的調用。這部分是普通的舊rspec。 – 2010-09-27 15:28:44

+0

我沒有使用你推薦的插件,而是使用這個http://www.slideshare.net/fnando/testando-rails-apps-com-rspec來測試特定的例程。但我仍然有一種感覺,你的方式可能是對的。所以我給了一個贊成票。 – Rohit 2010-09-28 13:46:39