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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With