我的第一个猜测是写几个测试:
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 这样的东西。但我认为你最终会自己写,因为你会有一些具体的需求。
问候