简体   繁体   中英

Rspec for begin ... rescue block in rails

I am writing a test which should verify that when the object creation saves, indeed the exception is caught.

begin
  object.create!(item)
rescue => exception
  exception.message
end

rspec

 expect{ exception.message }.to eq("Validation failed: Item name can't be blank")

output I got:

 Failure/Error: expect{ exception.message }.to eq("Validation failed: Item name can't be blank")
       You must pass an argument rather than a block to `expect` to use the provided matcher (eq "Validation failed: Item name can't be blank"), or the matcher must implement `supports_block_expectations?`.

Can anyone help me out?

You cannot test your code like that because the exception variable only exists in the rescue block. Instead, you need to call the method you want to test and add an expectation of what it should return.

Your example actually doesn't have such a method that could be called. I imagine that your method actually looks like this:

def do_stuff_with(object, item) 
  begin
    object.create!(item)
  rescue => exception
    exception.message
  end
end

Then you should be able to have an expectation like this:

expect(do_stuff_with(object, item)).to eq(
  "Validation failed: Item name can't be blank"
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM