Joshua Muheim
Joshua Muheim

Reputation: 13195

expect{...}.to raise_error also passes when no error is risen

I have the following spec:

describe EmailImport do
  describe "#format_x_priority" do
    specify { EmailImport.format_x_priority('5 (Lowest)').should eq(:low) }

    it "should raise an error when wrong argument is passed" do
      expect { EmailImport.format_x_priority('5 (Lowest)').to raise_error }
    end
  end
end

This should not pass, right? It's both times the same code, and one time it should result in :low, and one time it should result in an error. But interestingly, both pass! What am I doing wrong?

Just for the sake of completeness, here's my EmailImport.format_x_priority method:

def self.format_x_priority(priority)
  # 1 Highest; 2 High; 3 oder "" normal; 4 low; 5 lowest
  case priority
  when "1 (Highest)"
    Priority::HIGH
  when "2 (High)"
    Priority::HIGH
  when "3 (Middle)"
    Priority::MEDIUM
  when "4 (Low)"
    Priority::LOW
  when "5 (Lowest)"
    Priority::LOW
  when ''
    Priority::MEDIUM
  else
    raise "Invalid value '#{priority}' for argument 'priority'!"
  end
end

Upvotes: 0

Views: 210

Answers (2)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Syntax Error

You have a syntax error. You're enclosing the entire line, including the matcher, in the block. Move the curly brace to enclose just the lambda, and you should be back on track. For example:

it "should raise an error when wrong argument is passed" do
  expect { EmailImport.format_x_priority('5 (Lowest)') }.to raise_error
end

Why This Works

The specify keyword takes a block, so specify { ... } is correct. On the other hand, expect takes a lambda, and passes it to the matcher. That makes expect { ... }.to raise_error correct.

Upvotes: 2

Joshua Muheim
Joshua Muheim

Reputation: 13195

The solution lies in the details! Right code:

expect { EmailImport.format_x_priority('5 (Lowest)') }.to raise_error

Wrong code:

expect { EmailImport.format_x_priority('5 (Lowest)').to raise_error }

Upvotes: 0

Related Questions