loading words...

Jan 03, 2019 07:25:12

RSpec compound conditions

by @swizecteller | 200 words | 🐣 | 116💌

Swizec Teller

Current day streak: 0🐣
Total posts: 116💌
Total words: 32303 (129 pages 📄)

Today I learned how to write compound conditions in RSpec when writing tests for a Rails backend. #200wordsTIL

Say you have a method that returns an array. How do you check that it contains value1 OR value2? 🤔

There's the `includes` matcher. That lets you check that an array includes a value. You use it like this:

expect(my_result).to include(value1)

my_result is your method result, value1 is the value you're checking for.

So if my_result is something like [1,2,3,4] your test passes, if value1 is any of 1, 2, 3, or 4. Otherwise your test fails. 👍

Cool part of RSpec is how readable your tests come out.

Want to check for multiple values? Easy.

expect(my_result).to include(value1)

expect(my_result).to include(value2)

Now your test passes iff my_result includes both values.

You can also write expect(my_result).to include(value1, value2) to save space.

Ok so writing an AND is easy. But how do you make sure the result includes value1 OR value2?

There's a .or operator! 😱

expect(my_result).to include(value1).or include(value2)

You can chain as many .or as you want and you can use different matchers too. Very nice ✌️

Originally published at twitter.com

  • 1

    @swizecteller Welcome :) We can make an army of programmers on this website now ? !!

    Basile Samel avatar Basile Samel | Jan 03, 2019 20:15:03
contact: email - twitter / Terms / Privacy