Read more

Spreewald: When using `patiently do`, don't reuse existing variable names

Henning Koch
March 22, 2013Software engineer at makandra GmbH

Spreewald Show archive.org snapshot 's patiently repeats the given block again and again until it either passes or times out.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Be careful to give patiently a block that can actually be repeated. E.g. the following block can not be repeated:

Given /^the field "(.*?)" is empty$/ do |field|
  patiently do
    field = find_field(field)
    field.text.should be_blank
  end
end

The reason the above code will fail when repeated is that the block is reassigning the field variable that was defined outside of the block (it's the variable set from the Given block's arguments). Because of this, during the first repetition the value of field will actually be:

field = find_field(find_field(field))

And during the second repetition:

field = find_field(find_field(find_field(field)))

To not fall into this trap, do not reuse variable names that are defined outside the repeated block. To fix the example above, we will use two separate variables label and field:

Given /^the field "(.*?)" is empty$/ do |label| # ←
  patiently do
    field = find_field(label)
    field.text.should be_blank
  end
end

Note that you can of course reuse the names of variables that have been defined inside the repeated block.

Posted by Henning Koch to makandra dev (2013-03-22 17:01)