rubyunit-testingrspecpuppetrescue

How to test a simple rescue block in ruby


I have a custom fact in ruby that goes like this:

Facter.add(:some_random_fact) do
  setcode do
    output = execute_some_method
    if !output.nil? then
      begin
        pruned_output = output.split("\n")
        result = true
      rescue
        result = false
      end
    else
      result = false
    end
  end
end

How do I write a unit test using rspec for the rescue block to raise an Exception?

EDIT: Please let me know if the below test is the correct way to test it

it "return fact as false when begin block raises exception" do
    output = double(:output)
    allow(output).to receive(:split).with(true).and_raise(RuntimeError.new("error occured"))
    expect(Facter.fact(:some_random_fact).vallue).to eq(false)
end

Solution

  • The code you've shown here is weird and I get the feeling we're missing context, but in general you can stub out a method to raise an error like so:

    expect(output).to receive(:split).with("\n").and_raise(RuntimeError.new("some error"))
    

    but this is sort of an ugly way to go about things. If the error is raised conditionally depending the type of output, then it's better to find a way to set that variable to an error-producing value. How to do that, I can't tell you without seeing the test of your code.

    For example, say you wrapped all this code in a def add_fact(output) - then from your tests you could intentionally pass an error-causing value for the output, and you no longer need to stub split (which is a wierd thing to do). This pattern is known as "dependency injection".