2
\$\begingroup\$

I find myself using subject blocks in my tests to setup example because it is succinct. However is this considered bad form and can it have undesired consequences?

require 'spec_helper'

describe "stations/index" do


  before(:each) do
    stub_user_for_view_test
    assign(:stations, [
      stub_model(Station),
      stub_model(Station)
    ])

  end

  context "when not an admin" do
    subject {
      render
      rendered
    }

    it { should match /[s|S]tations/ }
    it { should have_selector('.station', :minimum => 2) }
    it { should_not have_link 'Edit' }
    it { should_not have_link 'Delete' }
  end

  context "when an admin" do

    subject {
      @ability.can :manage, Station
      render
      rendered
    }

    it { should have_link 'Edit' }
    it { should have_link 'Delete' }
  end

end
\$\endgroup\$
3
\$\begingroup\$

There are no unintended consequences, but it is a little unusual and may surprise the reader. However, it is a small surprise.

It usually communicates intent well to use subject to declare the subject, and before to setup preconditions unrelated to the subject. For preconditions that involve the subject, those are often better in a before block as well, but it's not too surprising to find them in the subject block.

So, instead of this:

subject {
  @ability.can :manage, Station
  render
  rendered
}

this:

before(:each) do
  @ability.can :manage, Station
  render
end

subject {rendered}

I used do...end for the multi line block and {} for the single line block; this is a common (although not ubiquitous) practice.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.