Shoulda教程之三—测试ActiveRecord模型

ActiveRecord助手方法

Shoulda具有一套ActiveRecord测试宏,这让开发效率大大提高,TDD变得轻而易举。关于这个方面的所有的文档都在Shoulda的Rdoc中。下面就来个小小的例子:

class UserTest :dogs
 should_belong_to :lover
end

上面的代码创建了如下的测试:

test: Person should allow phone_number to be set to “(123) 456-7890″.
test: Person should belong to lover.
test: Person should have many dogs.
test: Person should have many messes through dogs.
test: Person should have one profile.
test: Person should not allow admin to be changed by update.
test: Person should not allow phone_number to be set to “1234″.
test: Person should not allow phone_number to be set to “abcd”.
test: Person should require name to be set.
test: Person should require phone_number to be set.
test: Person should require unique value for name.

前提

一件需要知道的事情是一些ActiveRecord测试宏找到第一个初始的记录(通过 Class.find(:first))。你可以让这个工作通过一个具有一条记录的fixture文件,或者通过在setup中创建一条记录,类似下面这样:

class UserTest < Test::Unit::TestCase
 def setup
  @user = User.create!(params)
 end
 
 should_require_unique_attributes :name
end

或者通过一个context,如下:

class UserTest < Test::Unit::TestCase
 context "given an existing record" do
  setup do
   @user = User.create!(params)
  end
 
  should_require_unique_attributes :name
 end
end

但是Shoulda不止是提供了对模型的测试,还提供了很多强大的助手方法可以使用于控制器。

This entry was posted on 星期日, 05月 11th, 2008 at 1:28 pm and is filed under Agile, Ruby. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

没有评论

Be the first to comment on this entry.

Have your say

You must be logged in to post a comment.

Recent Posts:
  1. Blog已搬迁 - 2008-08-22
  2. a few interesting rails plugin - 2008-08-06
  3. Get Start Java Network App Dev - 2008-08-06
  4. 思考着Blog搬家 - 2008-07-28
  5. a bug in attachment_fu - 2008-07-28
  1. 我的梦想

    我的梦想是成为世界级的软件开发者。。。 联系我请mailto: chenk85 AT gmail.com 或者加我MSN: chenk85 AT live.cn
  2. 标签

  3.  

    05月 2008
    « Apr   Jun »
     123
    45678910
    11121314151617
    18192021222324
    25262728293031
  4. 文章分类

  5. 存档页

  6. 评头论足

    • 功能