论坛首页 编程语言技术论坛

Rails宝典七十一式:用RSpec测试你的Rails程序

浏览 4815 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-09-17  
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大餐,让我们来尝尝鲜:
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

这是一段测试MenuItemsController的代码,可读性强大到像是在talking,像是用我们的母语在“说”测试!
回想一下传统的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

唉,感觉到恶心了吧!

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

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

我们可以完全抛弃Rails自带的测试框架,拥抱RSpec!

所以,你还在用Rails那套老古董的测试框架吗?太落后了吧,JavaEye都用RSpec了,你用了吗?
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics