fpmmxw
Last Updated: February 25, 2016
·
916
· mcansky
892a174c18182a2a3157e51cd071d1cf

.clone & Ruby constants

Writing a simple Sinatra app to mock a webservice I decided to use rspec and a simple yaml file to store the test data needed.

The yaml file is loaded as the FIXTURES constant hash in my spec_helper.rb :

require 'yaml'
FIXTURES = YAML.load_file('config/fixtures.yml')

Then, in order to trigger specific test cases I decided to grab a copy of a specific hash in FIXTURES and alter something in that copy :

foo_hash = FIXTURES['some']['hash']
foo_hash['a_key'] = 'new string'

But then, since the sinatra routes use the same yaml file to grab data to return back and because the way constants are handled in Ruby ( http://www.ruby-forum.com/topic/67675) the content of the FIXTURES hash would change too.

To avoid that, one can then use the clone method :

foo_hash = FIXTURES['some']['hash'].clone

The clone method produce a totally separate copy of the hash, hence solving the problem.

Mystery solved.

Symptoms : rspec tests running in random order produce different results. Yet reusing a specific random seed will produce the same results over and over.

Say Thanks
Respond