How to check code that uses system commands

I am writing a simple library that checks that the mysql server is alive and dependent on the results, it does other things. To test the connection, I use this 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 check this method? I think I should not connect to the mysql server during the test. The only idea I have is to return the corresponding line command for ping to one method (depends on the password) and use it in the method, for example:

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

and in every test they only mock this method, so only this method uses the command.

What would you do to check it correctly?

+3
source share
2 answers

:

  • , parse_result .
  • Mock check_connection, mysqladmin.

, mysql , , . ping_string , , mysqladmin , .

+1

system (``), . , , :

class Thing
  def check_connection
    result = system "some command"
    parse_result result
  end
end

( rspec ) :

it 'should check the connection' do
  thing = Thing.new
  thing.should_receive(:system).and_return "some result"

  thing.check_connection
  # whatever checking you want to make with the parse_result method
end

, Kernel#system, . Thing , .

0

All Articles