Capturing a system call in ruby with backticks, while setting an environment variable 1

Posted by Tim Connor Wed, 20 Feb 2008 18:26:00 GMT

As you may know system() and `` both make system calls in ruby, but the second one captures the STDOUT for you, essentially, which is handy sometimes, like when testing. They don’t necessarily both do this by just a straight call to the commandline, but various internal utilities that make such thing possible in Windows too, for instance.

Well the problem with this is it can mess with your setting of an ENV as a precursor to your command. For instance, this is valid on my platform:


RAILS_ENV=test rake metric_fetcher

and works via system():

system(“RAILS_ENV=test rake metric_fetcher”)

but chokes in backticks, probably due to the aforementioned jiggering around for Windows compat:

`RAILS_ENV=test rake metric_fetcher`

Now you generally can just move the command back to the beginning of the line:

`rake RAILS_ENV=test metric_fetcher`

but if for some bizarre reason that doesn’t work for you (it’s probably something else going, wrong, though, to be honest) you can do this:

ENV[‘RAILS_ENV’]=‘test’; `rake metric_fetcher`

So ultimately, I can do this hacky wonder:


assert `rake RAILS_ENV=test metric_fetcher`.empty?

if my rake task succeeds silently and fails noisily (which is a useful characteristic for cron’ed tasks).

Thanks to Defiler and ocotpod for proving to me I really did have my head up my ass and that all but the leading env var in backticks form should work as expected.(fixture set-up issues as usual).

Addendum And if you are calling rake like this in a test and getting odd problems – consider turning transaction fixtures off.

Comments

Leave a comment

  1. Avatar
    Tim Connor 1 day later:

    fyi: I just added an article with the “proper” way of doing this by actually invoking the rake task from ruby

Comments