Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is the keyword "should" in RSpec Ruby

Tags:

ruby

rspec

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?

like image 361
woodstok Avatar asked May 23 '12 10:05

woodstok


People also ask

What is example in RSpec?

The word it is another RSpec keyword which is used to define an “Example”. An example is basically a test or a test case. Again, like describe and context, it accepts both class name and string arguments and should be used with a block argument, designated with do/end.

What is RSpec in Ruby?

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.

What is new keyword in Ruby?

To create a new object (or instance), we call new on the class. Unlike other languages, new isn't a keyword of the language itself, but a method that gets called just like any other. In order to customize the newly created object, it is possible to pass arguments to the new method.


2 Answers

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.

like image 60
Holger Just Avatar answered Oct 10 '22 12:10

Holger Just


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.

like image 44
Russell Avatar answered Oct 10 '22 10:10

Russell