Code duplication between nested contexts. How to avoid?

2 views
Skip to first unread message

sserdyuk

unread,
Sep 25, 2009, 12:29:32 AM9/25/09
to shoulda
Hi,

I am staring to use Shoulda+Webrat+FactoryGirl+... to do integration
tests. Things working good, but I am forced to write the same code
twice for situations where nested contexts are executed in state that
I also test for. Please take a look at 'should' "be able to login" and
setup in 'context' "when logged in". If have similar but much more
elaborate situations, where 20+ lines have to be duplicated, so it is
worth making it right.

What approach could be recommended in this situation?


class FacilitatorTest < ActionController::IntegrationTest

context "A Facilitator" do

setup do
@facilitator = Factory(:facilitator)
end

should "login before accessing events" do
get '/'
assert_redirected_to '/login'
end

should "be able to login" do
visit '/login'
fill_in 'Email', :with => @facilitator.email
fill_in 'Password', :with => 'password'
lambda { click_button 'Log in' }.should change { assigns
(:current_user) }.to(@facilitator)
end

context "when logged in" do

setup do
#session[:facilitator_user] = @facilitator.id
visit '/login'
fill_in 'Email', :with => @facilitator.email
fill_in 'Password', :with => 'password'
click_button 'Log in'
@event = Factory(:event)
end

should "see the event list" do
visit '/'
assert_template 'events/index'
end

François Beausoleil

unread,
Sep 25, 2009, 8:55:37 AM9/25/09
to sho...@googlegroups.com
Good old Extract Method refactoring?

class FacilitatorTest < ActionController::IntegrationTest

context "A Facilitator" do

setup do
@facilitator = Factory(:facilitator)
end

should "login before accessing events" do
get '/'
assert_redirected_to '/login'
end

should "be able to login" do
lambda { login_with :defaults }.should change { assigns
(:current_user) }.to(@facilitator)
end

context "when logged in" do

setup do
#session[:facilitator_user] = @facilitator.id
login_with :defaults
@event = Factory(:event)
end

should "see the event list" do
visit '/'
assert_template 'events/index'
end

def login_with(email=:defaults, password='password')
email = @facilitator.email if email == :defaults

visit '/login'
fill_in 'Email', :with => email
fill_in 'Password', :with => 'password'
click_button 'Log in'
end
end

Hope that helps!
--
François Beausoleil
http://blog.teksol.info/
http://piston.rubyforge.org/
Reply all
Reply to author
Forward
0 new messages