Development Blog

 Tuesday, July 01, 2008
« Rhino.Mocks Performance Issue Fixed | Main | MSpec v0.2 »

Mikel Lindsaar recently posted a tip encouraging rSpec users to not use before :each, and set up the context in every "it" specification.

I'm afraid I disagree. By pushing context setup into your specifications, you're allowing your contexts to become artificial and anemic and your specifications to become fat and more than just specifications.

Ultimately, this means that your reports will read poorly and it will be easy to introduce specifications in a context that do not match the others.

Mikel arrives at the following specs at the end of his post:

describe "when not logged in" do
  it "should redirect if we are not logged in" do
    get :index
    response.should redirect_to login_path

describe "when logged in" do
  def given_a_logged_in_user
    session[:logged_in] = true
    session[:user_id] = 99

  it "should let be a success" do
    get :index
    response.should be_success

  it "should render the index template" do
    get :index
    response.should render_template('people/index')
"when logged in" is not what I would consider a valid description of Mikel's context in these specs. I would call it something along the lines of "when visiting the index page while logged in". *That* is the context you are specifying against. Compare:

when logged in, it should render the index template


when visiting the index page while logged in, it should render the index template

The first is clearly missing something. Unless rendering the index template is a direct result of just *being* logged in, the spec is flawed.

With that in mind, as soon as you describe your context, there's no reason to not pull that context setup into a single before method. It forces you to use that context in every specification contained within your describe. It also makes your tests easier to read. You establish your context, and then you make one line specifications against that context.

I do agree that DRY should not be taken too far in tests. Base classes, helper methods, all that sort of thing can quickly obfuscate them, but do not forsake the context setup.
bdd | rspec | dry
by Aaron on Tuesday, July 01, 2008 7:04:07 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |  Trackback Related posts:
Getting ReSharper and VS to play nice with MSpec
BDD – Consider your audience
MSpec v0.2

Comments are closed.