What are people’s opinions on which of these two styles is better to
use?
- before
module UserSpecHelper
include GenericSpecHelper
def valid_sms_attributes(phone_number=“12345”)
{ :phone_number => phone_number }
end
end
describe User, “with phone number” do
include UserSpecHelper
before(:each) do
@user = User.new(valid_sms_attributes)
end
it “should be valid” do
@user.should be_valid
end
it “should reject duplicate phone number” do
@user.save
@user_2 = User.new(valid_sms_attributes)
@user_2.should_not be_valid
end
it “should be possible to disable the number” do
@user.save
@user.disable_number
@user.should be_disabled
end
end
- given/yield
module GenericSpecHelper
def given(thing)
yield thing if block_given?
thing
end
end
module UserSpecHelper
include GenericSpecHelper
def valid_sms_attributes(phone_number=“12345”)
{ :phone_number => phone_number }
end
def valid_sms_user(phone_number=“12345”)
User.new(valid_sms_attributes(phone_number))
end
end
describe User, “unconfirmed” do
include UserSpecHelper
it “should be valid” do
valid_sms_user.should be_valid
end
it “should reject duplicate phone number” do
valid_sms_user(“1”).save
valid_sms_user(“1”).should_not be_valid
end
it “should be possible to disable the number” do
given(valid_sms_user) do |user|
user.save
user.disable_number
user.should be_disabled
end
end
end
My thoughts: the second style is more readable sometimes, less other
times. More importantly, with the first style, my specs tend to be
split alongside the lines of whether they can use the same before
(:each), rather than whether they belong together, whereas with the
second one, one “description” can have several different “starting
points”, and I group them by whether I feel they belong together
logically. So at the moment I’m more comfortable with the second style.
What do you think?
Daniel
PS: I know these specs themselves are trivial… I’ve used both
approaches in less trivial specs, I hope these illustrate the idea
though