开发者

Ruby - FlexMock Backticks Method

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`开发者_StackOverflow
  if result.to_a.length > 0
    true
  else
    false
  end
end


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜