如何测试这个==> rspec + rails

时间:2010-09-27 13:54:20

标签: ruby-on-rails ruby 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

测试这部分代码

任何建议都是最受欢迎的。

P.S我在rspec很天真,所以请提醒我这个问题,如果答案很简单:)

1 个答案:

答案 0 :(得分: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

Remarkable-rails提供了上面使用的render_template,set_the_flash和redirect_to匹配器。