Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

ruby - How do I `expect` something which raises exception in RSpec?

I have a method which performs some actions on Cat model and in case of incorrect input raises an exception:

context "hungry cat" do
  it { expect { eat(what: nil) }.to raise_error } 
end

What I want to do is to check whether this method change cats status, like that:

context "hungry cat" do
  it { expect { eat(what: nil) }.to raise_error } 
  it { expect { eat(what: nil) }.not_to change(cat, :status) } 
end

The problem is that since eat(what: nil) will raise an exception the second it will fail no matter what. So, is it possible to ignore exception and check some condition?

I know that it's possible to do something like:

it do 
  expect do
    begin
      eat(what: nil)
    rescue
    end
  end.not_to change(cat, :status)
end

But it's way too ugly.

question from:https://stackoverflow.com/questions/16858899/how-do-i-expect-something-which-raises-exception-in-rspec

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use the "rescue nil" idiom to shorten what you already have:

it { expect { eat(what: nil) rescue nil }.not_to change(cat, :status) }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...