对Ruby on Rails进行高效的单元测试的教程

2019-09-25 09:43:43刘景俊

describe "create action" do
 it "should donot create new user with wrong params" do
  post :create
  response.should redirect_to(users_path)
  flash[:notice].should == "Create Fail!"
 end

 it "should create a new user with right params" do
  post :create, {:email => "abc@eleutian.com"}
  response.should redirect_to(users_path)
  flash[:notice].should == "Create Successful!"
 end
end

同时,也需要对controller的assigns进行测试,以保证返回正确的数据。如下例:

before(:each) do
 @course = Factory(:course)
end 

describe "show action" do
 it "should render show page when flag != assess and success" do 
  get :show, :id => @course.id, :flag =>"test"
  response.should render_template("show")
  assigns[:test_paper].should == @course
  assigns[:flag].should == "test"
 end

 it "should render show page when flag == assess and success" do
  get :show, :id => @course.id, :flag =>"assess"
  response.should render_template("show")
  assigns[:test_paper].should == @course
  assigns[:flag].should == "assess"
 end  
end

View的测试

View的测试代码写的比较少,基本上是把核心的view部分集成到controller中来测试。主要用integrate_views方法。如下例:

describe AccountsController do
 integrate_views
 describe "index action" do
  it "should render index.rhtml" do
   get :index
   response.should render_template("index")
   response.should have_tag("a[href=?]",new_account_path)
   response.should have_tag("a[href=?]",new_session_path)
  end
 end
end

总结展望

在写测试代码的时候,并不一定要事无巨细,有些比较简单的方法以及Rails的内部的方法,如named_scope,就完全没有必要测试。本文中,只介绍了用rspec写单元测试的代码,对于集成测试没有涉及,这也是今后努力的一个方向。

另外,用cumumber + rspec + webrat的BDD开发模式也是相当不错的。尤其是cumumber对需求的描述,完全可以用它来做需求分析。