在测试中,断言列表中项目属性的设计模式是什么?

时间:2013-05-24 19:53:33

标签: ruby-on-rails ruby testing rspec

我想断言(实际上是在rspec中)tags列表中至少有一项是非公开的。

it 'lets you select non-public tags' do
  get :new
  flag = false
  assigns(:tags).each do |tag|
    if tag.is_public == false
      flag = true
    end
  end
  flag.should eql true
end

做同样事情的更好,惯用的方法是什么?

2 个答案:

答案 0 :(得分:1)

有一百万种方法可以做到这一点:

# are any tags not public?
flag = assigns(:tags).any? { |tag| !tag.is_public }
flag.should eql true

# Are none of the tags public?
flag = assigns(:tags).none?(&:is_public)
flag.should eql true

# Find the first non-public tag?
flag = assigns(:tags).find { |tag| !tag.is_public}
flag.should_not eql nil

答案 1 :(得分:0)

这里有很多选择。也许:

assigns(:tags).reject { |tag| tag.is_public }.should_not be_empty