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
asked Nov 11, 2013 at 15:05
\$\endgroup\$

1 Answer 1

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.

answered Jan 8, 2014 at 16:30
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.