0

我一直在愉快地使用应该是这样的:

context "test world" do
  setup do
   @world = ...
  end

  should "be spinning" do
   assert_equal "spinning", @world.movement
  end

  ... and so on
end

我需要一个技巧来理解这种变化:

class PostTest < Test::Unit::TestCase
   should belong_to(:user)
   should have_many(:tags).through(:taggings)

   should validate_uniqueness_of(:title)
   should validate_presence_of(:body).with_message(/wtf/)
   should validate_presence_of(:title)
   should validate_numericality_of(:user_id)
 end

我不清楚的是各种“应该属于_to(:user)”等等的操作。换句话说,很明显它们是在 Post 的一个实例上运行的,但是是什么决定了它呢?'should xxx' 行的主题是什么?

我知道这是一个新手问题,所以任何指针都会很棒!

4

1 回答 1

2

shoulda 定义了许多单行断言,可以用来代替块,以使某些类型的测试更简洁。这些是关于 Active Record 模型的特定断言。

你是对的,这些断言的主题是一个 Post 对象。这是根据测试类的名称确定的。如果您想了解它,请查看源代码:

https://github.com/thoughtbot/shoulda/blob/master/lib/shoulda/context.rb

construct_subject方法去除 Test 后缀并实例化生成的类名。如果您对 Active Record 的特定单行断言感到好奇,请查看 Active Record 匹配器:

https://github.com/thoughtbot/shoulda/tree/master/lib/shoulda/active_record/matchers

于 2010-12-28T20:30:04.047 回答