3

使用 mocha gem 测试以下方法的最佳方法是什么?

def can_create?(user)
  opened? && (owner?(user) || member?(user))
end

测试“AND”和“OR”条件的最佳实践是什么?我应该创建许多测试来涵盖所有可能性,还是希望选项涵盖所有可能性?


我正在使用 rails 4 + 测试单元。

例如,当我仅使用 && 进行测试时:

def can_update?(user)
  opened? && owner?(user)
end

我正在测试:

group = Group.new
user  = User.new
group.expects(:opened?).returns(true)
group.expects(:owner?).returns(true)
assert group.can_update?(user)

问题是当我有“或”条件时。使用第一种方法( can_create? )我不能这样做:

group = Group.new
user  = User.new
group.expects(:opened?).returns(true)
group.expects(:owner?).returns(true)
group.expects(:member?).returns(true)
assert group.can_create?(user)

因为(所有者?和成员?方法可以是真/假)。

4

1 回答 1

0

我的第一个猜测是写几个测试:

test 'with opened and owner' do
  group = Group.new
  user  = User.new
  group.expects(:opened?).returns(true)
  group.expects(:owner?).returns(true)
  assert group.can_create?(user)
end

test 'with opened and member' do
  group = Group.new
  user  = User.new
  group.expects(:opened?).returns(true)
  group.expects(:owner?).returns(false)
  group.expects(:member?).returns(true)
  assert group.can_create?(user)
end

test 'with opened and not member or owner' do
  group = Group.new
  user  = User.new
  group.expects(:opened?).returns(true)
  group.expects(:owner?).returns(false)
  group.expects(:member?).returns(false)
  assert group.can_create?(false)
end

然后你可以重构你的测试以获得更干净的东西,所以你想使用存根而不是期望来避免 OR 问题:

def assert_can_create(params, expected)
  group = Group.new
  user  = User.new
  group.stubs(:opened?).returns(params[:opened])
  group.stubs(:owner?).returns(params[:owner])
  group.stubs(:member?).returns(params[:member])

  assert group.can_create?(expected)
end

test 'can_create possibilities' do
  assert_can_create({opened: true, owner: true, member:true}, true)
  assert_can_create({opened: true, owner: true, member:false}, true)
  assert_can_create({opened: true, owner: false, member:true}, true)
  assert_can_create({opened: true, owner: false, member:false}, false)
  assert_can_create({opened: false, owner: true, member:true}, false)
  [...]
end

毕竟,这个例子并不长。如果你有很多很多条件,你可能想要像 Aupajo 这样的东西。但我认为你最终会自己写,因为你会有一些具体的需求。

问候

于 2013-09-03T16:25:57.273 回答