Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force an RSpec test to fail?

What's the proper way to force an RSpec test to fail?

I'm considering 1.should == 2 however there's probably something better.

like image 924
SundayMonday Avatar asked Mar 07 '12 20:03

SundayMonday


People also ask

How do I cancel RSpec?

How to stop running tests on the first failed test (fail fast tests in RSpec)? You may add a parameter to tell RSpec to stop running the test suite after N failed tests, for example: --fail-fast=3 . There is a downside to it.

Is RSpec BDD or TDD?

RSpec is a Behavior-Driven Development tool for Ruby programmers. BDD is an approach to software development that combines Test-Driven Development, Domain Driven Design and Acceptance Test-Driven Planning. RSpec helps you do the TDD part of that equation, focusing on the documentation and design aspects of TDD.

Does RSpec clean database?

I use the database_cleaner gem to scrub my test database before each test runs, ensuring a clean slate and stable baseline every time. By default, RSpec will actually do this for you, running every test with a database transaction and then rolling back that transaction after it finishes.

What is RSpec capybara?

Capybara helps you test web applications by simulating how a real user would interact with your app. It is agnostic about the driver running your tests and comes with Rack::Test and Selenium support built in.


1 Answers

fail/raise will do the trick (they are aliases of each other).

Example

specify "this test fails" do   raise "this is my failure message" end 

Fails with:

1) failing this test fails    Failure/Error: raise "this is my failure message"     RuntimeError:      this is my failure message 

Alternatives

If you are thinking of using raise/fail in a spec, you should consider that there are probably more explicit ways of writing your expectation.

Additionally, raise/fail doesn't play well with aggregate_failures because the exception short-circuits the block and won't run any following matchers.

Mark a test as pending

If you need to mark a test as pending to make sure you get back to it, you could use the fail/raise, but you can also use pending.

# 🚫 Instead of this: it "should do something" do    # ...    raise "this needs to be implemented" end  # βœ… Try this: it "should do something" do   pending "this needs to be implemented" end 

Assert that a block is not called

If you need to ensure a block is not being executed, consider using the yield matchers. For example:

describe "Enumerable#any?" do   # 🚫 Instead of this:   it "doesn't yield to the block if the collection is empty" do     [].any? { raise "it should not call this block" }   end    # βœ… Try this:   it "doesn't yield to the block if the collection is empty" do     expect { |b| [].any?(&b) }.not_to yield_control   end end 
like image 126
nicholaides Avatar answered Sep 23 '22 10:09

nicholaides