Last Updated: February 25, 2016
·
511
· adambird

Randomise variables for testing

Whenever I'm testing I like to use randomised variables that I can later inspect to confirm an operation without risk of magic variables masking failure. In this simple example

name = "Bill"
account = Account.new(name: name)
account.name.should eq(name)

I would replace "Bill" as follows

name = random_string
account = Account.new(name: name)
account.name.should eq(name)

This approach allows me to be more confident that I'm testing behaviour rather than fixtures setup.

In order to streamline this I've created several helper methods that I include in my test suites. The random_string method would look something like this

def random_string
  (0...24).map{ ('a'..'z').to_a[rand(26)] }.join
end

I've shared a series of them here

https://gist.github.com/adambird/5582273