Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rspec expect condition OR condition

How do I write rspec tests defensively, so that in a scenario at least one expectation must be met yet the failure of others is accepted? (without the input changing). AND is easy enough by listing multiple expectations, but how is OR expressed?

As an example, a user has many posts, and user Bob hacks a form so that when he submits his create post form it sends the id of user Dunc. Currently the application ignores the passed Dunc id, and uses Bob's id as Bob is creating the post. So we could test that the newly created Post has Bob's user_id. However, if in future the code is refactored so that it returns an error message instead of assuming Bob's id, that test would wrongly fail. I want to test the intent, not the implementation.

So i need to test that either no post is created, or that if one is created, its for Bob.

This example is so simple it can be solved by testing

expect { run }.not_to change( Post.where(user_id: @other_user.id), :count )

However I'm looking for the general solution, in more complex cases there can be many conditions. How is "OR" achieved in Rspec? (or is it not possible?)

like image 884
xxjjnn Avatar asked Jul 14 '26 13:07

xxjjnn


1 Answers

I don't think it is possible.

I do think you are mistaken when you say that you would be testing implementation, instead of intent in your example.

When you write a test, you test whether what comes out matches your expectation.

Creating a user is something completely different than returning error messages.

In my opinion it would be strange to say: when I do this, I expect this, or that, or that, or that to happen.

In my opinion you should write one test, that tests whether a user is created when you send the correct parameters, and another test that deals with what happens when a user tries to send illegal parameters.

like image 188
Arjan Avatar answered Jul 17 '26 16:07

Arjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!