Tuesday, October 16, 2012

ActiveRecord, JSON & hashes

While testing a new script for some data loading, I found myself on our testing platform and stymied because the foundation things I needed were not part of that database.  I needed certain license records and Forge records.  While the staging system has a more or less complete copy of our production system, the testing system has a much more constrained data set.  This is a one of my bugaboos: making sure there is sufficient data for testing. And, once again, I questioned the decision to NOT use TDD for the script development.  That way, I could have mocked all the scenarios I needed and probably would have completed the script in less time to a greater level of quality.  But I digress.

I was in the console of the testing environment (not the "test" environment) and needed to have a particular license as part of the testing dataset.  I wanted to use the tools I had, not have to write a migration, start up PSQL, or any of those pathways.  I wanted to be lazy and get the record from the staging environment and copy it into the testing environment.

So, I found the license in the staging environment and converted it to json with license.to_json. That was wicked easy.  The next step was to parse the JSON, which will convert it to a hash, then extract the license value. That looks like this:

license_hash = JSON.parse(json)['license']

The result was a pretty little hash with all the necessary data that could be copied from one console to the next and then pasted into place.  In no time at all, I had the needed record in the testing database.

No comments:

Post a Comment