[rspec-users] Stubbing Kernel.` (backquote)

George Anderson george at benevolentcode.com
Wed Oct 24 13:42:30 EDT 2007


I found an alternate route, which may or may not work for others.

Instead of using Kernel#` (backquote / backtick), you might be able to
use Kernel#system.  The difference:

Kernel#` returns the standard output of running the command in a subshell

Kernel#system returns true if the command was found and executed
successfully, otherwise false.

So, in my case, I used:

class Barcode
 ...
 def raw_barcodes
    self.make_temporary_copy
    system("OcrBarcode #{self.temp_file_path}")
    ...
 end
 ...
end

describe "Calling @barcode.raw_barcodes" do
  before(:each) do
    File.stub!(:exist?).and_return(true)
    @barcode = Barcode.new('path/to/valid.pdf')
    Kernel.stub!(:system).and_return(true)
    FileUtils.stub!(:cp)
  end
  it "should make a copy of the file" do
    @barcode.should_receive(:make_temporary_copy)
    @barcode.raw_barcodes
  end
  ...
end

Note, my spec has changed a bit since my original post, but the gist remains.

I hope this helps someone down the line.

If you have a better way of spec'ing calls to a subshell, I'd live to hear it.

/g
On 10/24/07, George Anderson <george at benevolentcode.com> wrote:
> I'm trying to stub(!) the Kernel.` (backquote) method and I'm having
> confusing (to me) results. Here's the method I'm spec'ing:
>
> class Barcode
>   ...
>   def raw_barcodes
>     self.make_temporary_copy
>     `OcrBarcode #{self.temp_file_path}`
>   end
>   ...
> end
>
> And this is my (newbish) attempt at the spec:
>
> describe "Calling @barcode.raw_barcodes" do
>   before(:each) do
>     File.stub!(:exist?).and_return(true)
>     @barcode = Barcode.new('path/to/valid.pdf')
>     Kernel.stub!('`'.to_sym)
>   end
>   it "should make a copy of the file" do
>     @barcode.should_receive(:make_temporary_copy)
>     @barcode.raw_barcodes
>   end
>   it "should make a system call to OcrBarcode"
>   it "should make the system call to OcrBarcode passing in the
> temporary copy of the file"
>   it "should create foo.pdf.barcode"
> end
>
> When I run this (using cmd-d in the TM bundle), the test passes, but I
> get this line injected about the green "should make a copy of the
> file":
>
> /Users/george/work/simplify_md/vendor/plugins/rspec/lib/spec/mocks/proxy.rb:129:
> command not found: OcrBarcode
> /Users/george/work/simplify_md/tmp/valid_2007_10_24_111354_EDT.pdf
>
> (all one line)
>
>
> Significantly, if I remove the stub (Kernel.stub!('`'.to_sym)), I get
> the same result: passing with the same "command not found" message.
>
> Is there an accepted way to stub subshell calls?
>
> Thanks,
>
> /g
>
> --
>
> George Anderson
>
> BenevolentCode LLC
> O: (410) 461-7553
> C: (410) 218-5185
>
> george at benevolentcode.com
>


-- 

George Anderson

BenevolentCode LLC
O: (410) 461-7553
C: (410) 218-5185

george at benevolentcode.com


More information about the rspec-users mailing list