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

本文介绍RSpec结合Mocha为Rails应用程序提供的一种更为直观且易于理解的测试方式。通过RSpec的领域特定语言(DSL),开发者可以编写出如同自然语言描述般的测试案例,显著提高测试代码的可读性和维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Rails虽然自带有Controller、Model、Integration的测试框架,但是用起来感觉很枯燥无味
所以,你应该试试[url=http://rspec.rubyforge.org]RSpec[/url]+[url=http://mocha.rubyforge.org/]Mocha[/url]这道纯正的[url=http://clarkware.com/cgi/blosxom/2007/09/08#TestingControllers]墨西哥菜[/url]

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大餐,让我们来尝尝鲜:
[code]
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
[/code]
这是一段测试MenuItemsController的代码,可读性强大到像是在talking,像是用我们的母语在“说”测试!
回想一下传统的Controller测试:
[code]
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
[/code]
唉,感觉到恶心了吧!

如果你想测试你的Rails应用,你应该看看这份文档:[url=http://rspec.rubyforge.org/documentation/rails/index.html]RSpec::Rails[/url]

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

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

所以,你还在用Rails那套老古董的测试框架吗?太落后了吧,[url=http://robbin.iteye.com/blog/113056]JavaEye都用RSpec了[/url],你用了吗?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值