RSpec Example Building

January 26, 2010

Some stuff I´ve learned while reading the RSpec book, which is very good as the latest beta version.

  • describe and context are synonyms. Describe is better for actions and Context is better for hm.. well.. contexts! They work by supplying a string that describe the behavior you are trying to test (or a reference to a class or a Module) and a code block where the expectations should be placed.
    # some google code...
    describe User do
    describe "should not be chinese" do
    [...]
    
  • RSpec supports “nesting” to give context to your tests!
  • The it() method takes a string, an optional hash and an optional code block.
  • it() called with no block is marked as pending. Experienced developers recommend writing down everything you want the application to do, even when developing some other code if you remember something you missed, and leave it as pending until you get to it. Very easy to do, isn´t it?
  • Other ways to set a description to pending is by calling the pending() method inside of it. It even supports a code block that gets executed even with the description pending. If the code block succeeds, RSpec alerts you that it has been implemented (actually, it says it is fixed).
  • RSpec provides a before() method that takes supplied code block to be executed before all of the examples inside the context or before each of them. The only argument it takes is :all or :each. It´s highly recommended that you use :each as it starts a new context when checking an example.
  • The counterpart of the before method is the.. Hmm.. you guessed! The after method. It´s basically the same thing with the same arguments, except it runs after the examples have been executed, even if errors or exceptions are raised.
  • You can create helper methods that are methods defined inside the context that can be used by all the examples inside that context. It´s useful to keep things clean and DRY-compliant (Don´t Repeat Yourself). However, the goal is to make things clean but without loosing the readability. Keep things consistent!
  • To share helper methods across contexts, you can create a module with the methods and then include the module within the context.
  • You can share examples too! just start the example with shared_examples_for “name” do […] end and then call it within the context by using the it_should_behave_like “name” method.
  • Another way to share examples is by creating example modules, with the share_as :Name do […] end method. When needed, just include the created module inside the context by calling include Name.
Advertisements