rleber rleber - 1 year ago 76
Ruby Question

Is there a way to set the value of $? in a mock in Ruby?

I am testing some scripts that interface with system commands. Their logic depends on the return code of the system commands, i.e. the value of $?. So, as a simplified example, the script might say:

def foo(command)
if $?==0

In order to be able to test these methods properly, I would like to be able to stub out the Kernel backquote call, and set $? to an arbitrary value, to see if I get appropriate behavior from the logic in the method after the backquote call. $? is a read-only variable, so the following doesn't work:

$? = some_number

I can do some simple stuff: for example, set $? to zero or non-zero. For instance, will set $? to either 0 or 35212 (on my system, anyway), depending on the value of $?:

def fail_or_succeed(success)
if success
`echo foo`
`a-non-existent-command 2>&1`

What I'd really like to be able to do is to set $? to a specific value (e.g. 3, or 122), not just zero or an arbitrary non-zero. I can't figure out a way to do this. (In case it matters, I'm testing using Test::Unit and Mocha.)

Answer Source

EDIT: Using Dennis Williamson's suggestion:

command = "(exit 21)"

and use if $?.exitstatus == 0 instead of if $? == 0

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download