Search code examples
rubyrspecmockingrspec2

Ruby rspec Mocking a class


I have a file with two classes in it.

class LogStash::Filters::MyFilter< LogStash::Filters::Base

and

class LogStash::JavaMysqlConnection

JavaMysqlConnection has methods initialize and select. It is in use by the MyFilter class, and is used to query the database as you may have guessed.

How do I mock the initialize and select methods to return nil and an array respectively?

I tried using:

before(:each) do
  dbl = double("LogStash::JavaMysqlConnection", :initialize => nil)
end

but this did not work, as I am still seeing a communication link failure.

I have rspec version 2.14.8

Thanks in advance. PS. I am new to Ruby


Solution

  • Following on from Andrey's response, the solution that worked for me was:

     before(:each) do
        mock_sql = double(:select=> sql_select_return)
        allow(LogStash::JavaMysqlConnection).to receive(:new).and_return(mock_sql)
    end