繁体   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