Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec: Should be (this or that)

Tags:

ruby

rspec

What would be the best way to write the rspec in a situation where either of two (or more) outcomes are acceptable?

Here's an example of what I want to do. This is obviously wrong (I think), but it should give you the gist of what I'm trying to accomplish:

it "should be heads or tails" do   h="heads"   t="tails"   flip_coin.should be(h || t) end 

And yes, I'm aware I could write my own rspec matcher "should_be_one_or_the_other(option1,option2)", but that seems a bit much - I was hoping for a better solution.

like image 380
GlyphGryph Avatar asked Oct 27 '11 21:10

GlyphGryph


People also ask

What is expect in RSpec?

RSpec::Expectations provides a simple, readable API to express the expected outcomes in a code example. To express an expected outcome, wrap an object or block in expect , call to or to_not (aliased as not_to ) and pass it a matcher object: expect(order. total).

What is Shoulda Matchers?

Shoulda Matchers is a Ruby testing gem, that provides RSpec- and Minitest-compatible one-liners that test common Rails functionality. These tests would otherwise be much longer, more complex, and error-prone. COACH: Talk about testing and Behavior-Driven Development.

What is RSpec used for?

RSpec is a testing tool for Ruby, created for behavior-driven development (BDD). It is the most frequently used testing library for Ruby in production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool which you can start using rather quickly.

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.


1 Answers

ActiveSupport provides Object#in? method. You can combine it with RSpec and simply use the following:

flip_coin.should be_in(["heads", "tails"]) 

Or with new Rspec 3 syntax:

expect(flip_coin).to be_in(["heads", "tails"]) 
like image 189
Sergey Potapov Avatar answered Oct 13 '22 15:10

Sergey Potapov