Ruby multiple assignment to create unit test data

Julian Doherty

One of the tedious parts of writing unit tests is populating varying test data. Often you can wrap it all up into an array and iterate over it, other times you’re more interested in the individual objects and their interactions.

It’s not hard, but it takes up a few lines initializing each one separately. Less typing is better! Luckily, you can use Ruby’s multiple assignment operator to map all the objects you need in one hit to make your life easier:

def test_exam_result
  a,b,c,d,e,f = ('A'..'F').map{|v| MyObject.new(v)}

  assert stuff(a,b,c)
  assert other_stuff(c,b,f)
  assert d_hates_a(d,a)
end

Leave a Reply