How to test %x[] calls?

D

David Palm

Hi all,
how can I set an expectation on an external command execution?

Code:
def do_stuff(arg)
%x(external_executable_name #{arg})
end

Test (not working):
it "shells out and executes 'external_executable_name' with a bunch of nifty options" do
Kernel.should_receive:)`).with("external_executable_name argy args")
@worker.do_stuff("argy args")
end

If I change the code to:

def do_stuff(arg)
Kernel.`(external_executable_name #{arg})
end

...the test passes.

If I change the code to:

def do_stuff(arg)
`(external_executable_name #{arg})`
end

...the test fails.

Any other ideas? I could use Kernel#system() of course, but then I'd lose the output (or I'd have to go through the hoops of redirecting and reading etc, which I'd prefer to avoid). Why can't I test for the original %x?
 
B

Brian Candler

I guess it's because Kernel isn't the receiver of the call. It's the
top-level main object (of class Object, which mixes in Kernel)
yay!
=> nil
 
B

Brian Candler

... or inside your own object, it's that object which is the receiver
(which is ultimately subclassed from Object, which mixes in Kernel)

$ cat zog.rb
class Foo
def boing(x)
puts "boing #{x.inspect}"
end
alias :"`" :boing

def bar
%x{hello}
end
end

Foo.new.bar
$ ruby zog.rb
boing "hello"

So I think you should be able to set the expectation on your own object
- as long as you can do that for private methods.
 
D

David Palm

... or inside your own object, it's that object which is the receiver
(which is ultimately subclassed from Object, which mixes in Kernel)

$ cat zog.rb
class Foo
def boing(x)
puts "boing #{x.inspect}"
end
alias :"`" :boing

def bar
%x{hello}
end
end

Foo.new.bar
$ ruby zog.rb
boing "hello"

So I think you should be able to set the expectation on your own object
- as long as you can do that for private methods.

Totally works! You rock! :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top