诗歌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大餐,让我们来尝尝鲜:
这是一段测试MenuItemsController的代码,可读性强大到像是在talking,像是用我们的母语在“说”测试!
回想一下传统的Controller测试:
所以,你应该试试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大餐,让我们来尝尝鲜:
- describe MenuItemsController, "creating a new menu item" do
- integrate_views
- fixtures :menu_items
- it "should redirect to index with a notice on successful save" do
- MenuItem.any_instance.stubs(:valid?).returns(true)
- post 'create'
- assigns[:menu_item].should_not be_new_record
- flash[:notice].should_not be_nil
- response.should redirect_to(menu_items_path)
- end
- it "should re-render new template on failed save" do
- MenuItem.any_instance.stubs(:valid?).returns(false)
- post 'create'
- assigns[:menu_item].should be_new_record
- flash[:notice].should be_nil
- response.should render_template('new')
- end
- it "should pass params to menu item" do
- post 'create', :menu_item => { :name => 'Plain' }
- assigns[:menu_item].name.should == 'Plain'
- end
- end
回想一下传统的Controller测试:
- class MenuItemsControllerTest < Test::Unit::TestCase
- def setup
- @controller = MenuItemsController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
- def test_create_with_valid_menu_item
- assert_difference(MenuItem, :count, 1) do
- post :create, :menu_item => {:name => 'Classic',
- :price => 4.99}
- end
- assert_not_nil assigns(:menu_item)
- assert_not_nil flash[:notice]
- assert_redirected_to menu_items_url
- end
- def test_create_with_invalid_menu_item
- assert_difference(MenuItem, :count, 0) do
- post :create, :menu_item => { }
- end
- assert_not_nil assigns(:menu_item)
- assert_nil flash[:notice]
- assert_response :success
- assert_template 'new'
- end
- end
RSpec对Rails的Controllers、Models、Views、Helpers、Plugin、Integration等等测试都已经支持的很好或者即将支持
RSpec这套专有DSL,再加上Mocha这一强大的mocking和stubbing库,简直就是珠联璧合,所向无敌了!
Rspec集成Mocha
关键字: rspec mocha如果你想测试你的Rails应用,你应该看看这份文档:RSpec::Rails
莫愁前路无知己,天下无人不识君。