诗歌rails之用RSpec测试你的Rails程序

Rails虽然自带有Controller、Model、Integration的测试框架,但是用起来感觉很枯燥无味
所以,你应该试试RSpec+Mocha这道纯正的墨西哥菜

RSpec is a framework which provides programmers with a Domain Specific Language to describe the behaviour of
Ruby code with readable, executable examples that guide you in the design process and serve well as both
documentation and tests.

RSpec针对我们Ruby以及Rails的测试工作精心制作了一套独具风味的DSL大餐,让我们来尝尝鲜:
ruby代码
  1. describe MenuItemsController, "creating a new menu item" do  
  2.   integrate_views  
  3.   fixtures :menu_items  
  4.   
  5.   it "should redirect to index with a notice on successful save" do  
  6.     MenuItem.any_instance.stubs(:valid?).returns(true)  
  7.     post 'create'  
  8.     assigns[:menu_item].should_not be_new_record  
  9.     flash[:notice].should_not be_nil  
  10.     response.should redirect_to(menu_items_path)  
  11.   end  
  12.   
  13.   it "should re-render new template on failed save" do  
  14.     MenuItem.any_instance.stubs(:valid?).returns(false)  
  15.     post 'create'  
  16.     assigns[:menu_item].should be_new_record  
  17.     flash[:notice].should be_nil  
  18.     response.should render_template('new')  
  19.   end  
  20.   
  21.   it "should pass params to menu item" do  
  22.     post 'create', :menu_item => { :name => 'Plain' }  
  23.     assigns[:menu_item].name.should == 'Plain'  
  24.   end  
  25.   
  26. end  
这是一段测试MenuItemsController的代码,可读性强大到像是在talking,像是用我们的母语在“说”测试!
回想一下传统的Controller测试:
ruby代码
  1. class MenuItemsControllerTest < Test::Unit::TestCase  
  2.     
  3.   def setup  
  4.     @controller = MenuItemsController.new  
  5.     @request    = ActionController::TestRequest.new  
  6.     @response   = ActionController::TestResponse.new  
  7.   end  
  8.   
  9.   def test_create_with_valid_menu_item  
  10.     assert_difference(MenuItem, :count, 1do  
  11.       post :create, :menu_item => {:name => 'Classic',   
  12.                                    :price => 4.99}  
  13.     end  
  14.         
  15.     assert_not_nil assigns(:menu_item)  
  16.     assert_not_nil flash[:notice]  
  17.     assert_redirected_to menu_items_url  
  18.   end  
  19.     
  20.   def test_create_with_invalid_menu_item  
  21.     assert_difference(MenuItem, :count, 0do  
  22.       post :create, :menu_item => { }  
  23.     end  
  24.     
  25.     assert_not_nil assigns(:menu_item)  
  26.     assert_nil flash[:notice]  
  27.     assert_response :success  
  28.     assert_template 'new'  
  29.   end  
  30.   
  31. end  

RSpec对Rails的Controllers、Models、Views、Helpers、Plugin、Integration等等测试都已经支持的很好或者即将支持
RSpec这套专有DSL,再加上Mocha这一强大的mocking和stubbing库,简直就是珠联璧合,所向无敌了!

Rspec集成Mocha

关键字: rspec mocha
Rspec
Mocha
集成方法就是在spec_helper.rb里配置一下:
ruby代码
  1. config.mock_with :mocha  

这样就可以在Rspec测试中使用Mocha了


如果你想测试你的Rails应用,你应该看看这份文档:RSpec::Rails

posted @ 2009-07-10 14:44  麦飞  阅读(2596)  评论(0编辑  收藏  举报