# Using RSpec subject to setup a test

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

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

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

end


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.

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.