woodstok
woodstok

Reputation: 2794

What exactly is the keyword "should" in RSpec Ruby

I am a beginner in Ruby and had this question nagging me for a long time.

In an RSpec file , if we write Book.should <do something> , what is the should keyword? Is it a member of the Book object? How did it come to be the member of the Book object? Or is it some construct of Ruby? Is it a function? Where can i find the definition of this if it is a function or member?

Upvotes: 12

Views: 5598

Answers (2)

Holger Just
Holger Just

Reputation: 55833

Upon loading, RSpec includes a module into the Kernel module which is included into all objects known to Ruby. Thus, it can make the should method available to all objects. As such, should is not a keyword (like if, class, or end) but an ordinary method.

Note that that mixin is only available in RSpec contexts as it is "patched in" during loading or RSpec.

Upvotes: 13

Russell
Russell

Reputation: 12439

I've answered a similar question to this here. Basically:

What I think Holger's answer could make more explicit, and what may be what initially confused you, is that should breaks most of the usual conventions for method naming (nothing about the method describes what it does, for example) in order to make the code as a whole read as a sort of sentence.

So rather than just creating a set of tests, the library is trying to encourage you to describe your application through tests in a way that resembles a human-readable specification.

Upvotes: 3

Related Questions