开发者

generic function to test if objects in enumeration contain a property, and if it is equal to 10

In my test cases, I want to loop through a collection of objects (different objects, depending on the scenerio), and if the objects in the collection contain the property location_id I want to verify 开发者_运维百科the id has a value of e.g. 10

All the objects in the collection will be of the same type, but not all collections will have the same type i.e. some may be a collection of users, or a collection or articles etc.

I need this for my rspec tests.


Assuming that by "contain a property" means "responds to a getter method":

def test_for_value( collection, getter_method, value )
  # Only look deeper if the collection isn't empty
  # and the first element has the method
  if (o=collection.first) && o.respond_to?( getter_method )
    collection.find{ |o| o.send(getter_method)==value }
  end
end

Person = Struct.new( :name, :age )

people = []
p test_for_value( people, :age, 38 )
#=> nil

people << Person.new( "Gavin", 38 )
people << Person.new( "Imogen", 5 )

p test_for_value( people, :age, 38 )
#=> #<struct Person name="Gavin", age=38>

p test_for_value( people, :age, 5 )
#=> #<struct Person name="Imogen", age=5>

p test_for_value( people, :horns, true )
#=> nil

If instead you are talking about collections of hashes and you want to lookup the hash key:

def test_for_value( collection, key, value )
  if (o=collection.first) && o.key?( key )
    collection.find{ |o| o[key]==value }
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜