Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test code that uses system commands

Im writing simple library that check's that mysql server is alive and dependent from results, it do other things. To check connection, I use such code:

def check_connection
  result = if @password
    `mysqladmin -u#{@username} -p#{@password} ping`
  else 
    `mysqladmin -u#{@username} ping` 
  end
  parse_result(result)
end

How to test this method? I think, I should not connect to mysql server during the test. Only idea I have is to return in one method appropriate string command for ping (depends of password usage) and use it in method like:

def check_connection(ping_string)
  `#{ping_string}`
end

and in every test only mock this method, thus only this method use command.

What would you do to test it properly?

like image 828
Sławosz Avatar asked Aug 29 '26 19:08

Sławosz


1 Answers

You can stick with your original code, and approach it like this:

  1. Make sure that parse_result is unit tested.
  2. Mock check_connection so that the rest of your tests don't end up triggering a call to mysqladmin.

There's a hole in that the connection to mysql itself isn't tested, but I don't think that's a big deal. Testing ping_string won't really plug that hole, and given that the call to mysqladmin is basically hard coded your risk here is small.

like image 106
jdl Avatar answered Aug 31 '26 09:08

jdl