Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - FlexMock Backticks Method

Tags:

ruby

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
like image 692
Chris Bunch Avatar asked Aug 30 '26 01:08

Chris Bunch


2 Answers

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.

like image 157
Chris Bunch Avatar answered Aug 31 '26 18:08

Chris Bunch


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

like image 23
pierrotlefou Avatar answered Aug 31 '26 16:08

pierrotlefou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!