tags:

views:

163

answers:

3

I have Ruby code that uses the backticks in a number of spots and want to test it out. I'm using FlexMock and want to mock that method somehow. I know the method is Kernel, :` but can't seem to get it to work with FlexMock. How would you do this? Here's a sample of a method I want to test:

def foo
  result = `ls`
  if result.to_a.length > 0
    true
  else
    false
  end
end
+1  A: 

I know nothing about flexmock, but you might want to look at this.

pierr
Hmm, I could use something similar to this, but it makes a lot of work that flexmock is designed to get around. Part of the problem is that the ` method is just named differently than standard methods so flexmock's internal regex doesn't think it's a real method, but +1 for the good idea though. Thanks!
Chris Bunch
A: 

So it turns out the backticks method specifically maps to Kernel.`, which is fine until one looks at the FlexMock source to see what they consider to be valid method names. The regex they use essentially is checking for alphanumeric with ? or ! at the end, so backtick fails to match this regex.

Changing the code internally resolves the initial exception that is thrown, but doesn't actually make the code work as intended. I could have monkeypatched it as pierr suggested, but that would be extremely repetitive in my testing code, so I went the alternate route and just made a shell method in my library code that only does the backticks. This method then can be mocked out in the desired fashion, and since I only use the backticks in a small number of places, not a lot of my underlying code had to be changed.

Chris Bunch
A: 

You should call

Kernel.` "cmd"

instead of using

  `cmd`

on your code. Then you can test like this:

it "should call system ls" do
  Kernel.should_receive(:`).with("ls")
  Kernel.` "ls"
end

this example uses pure rspec

Daniel Cukier
Yes, as my answer says though, flexmock doesn't allow for backticks to be in mocked method names, so while it may work for rspec, it doesn't work for flexmock. Thanks though!
Chris Bunch