How do you check for code that uses forks with rspec

I have the following code

  def start_sunspot_server
    unless @server
      pid = fork do
        STDERR.reopen("/dev/null")
        STDOUT.reopen("/dev/null")
        server.run
      end

      at_exit { Process.kill("TERM", pid) }

      wait_until_solr_starts
    end
  end

How can I effectively test it with rspec?

I thought something

Kernel.should_receive(:fork)
STDERR.should_receive(:reopen).with("/dev/null")
STDOUT.should_receive(:reopen).with("/dev/null")
server.should_receive(:run)

etc.

+3
source share
2 answers

I am confused by the instance variable @serverand serverin your example, but here is an example that should help you get where you're trying to:

class Runner
  def run
    fork do
      STDERR.reopen("/dev/null")
    end
  end
end

describe "runner" do
  it "#run reopens STDERR at /dev/null" do
    runner = Runner.new

    runner.should_receive(:fork) do |&block|
      STDERR.should_receive(:reopen).with("/dev/null")
      block.call
    end

    runner.run
  end
end

The key is that the message is forksent to the object itself Runner, although its implementation is in the module Kernel.

NTN, David

+10
source

David's solution did not work for us. Maybe because we do not use RSpec 2?

Here is what worked.

def run
  fork do
    blah
  end
end

describe '#run' do
  it 'should create a fork which calls #blah' do
    subject.should_receive(:fork).and_yield do |block_context|
      block_context.should_receive(:blah)
    end

    subject.run_job
  end
end

, , STDERR, , .

+1

All Articles