I have a Rails app using AuthLogic and have gotten it to the point of using test doubles to step in for the current_user. There are a limited set of states for the current_user that are used repeatedly in many controller specs.
Continuing from this example, imagine controllers with similar double setup in each context. You can see that’s a lot of repeated code. What’s the preferred way for applying some DRY for this?
controller_1_spec.rb
require 'spec_helper'
describe Controller1 do
describe "GET 'index'" do
context "when user has state A" do
before(:each) do
user = double("User")
user.stub(:state).and_return("A")
user_session = double("UserSession")
user_session.stub(:user).and_return(user)
UserSession.stub(:find).and_return(user_session)
end
it "should test something for users with State A" do
get :index
end
it "should test something else for users with State A" do
get :index
end
end
context "when user has state B" do
before(:each) do
user = double("User")
user.stub(:state).and_return("B")
user_session = double("UserSession")
user_session.stub(:user).and_return(user)
UserSession.stub(:find).and_return(user_session)
end
it "should test something for users with State B" do
get :index
end
it "should test something else for users with State B" do
get :index
end
end
end
end
Is the best way just to add helper methods to spec_helper or is there something more best practice like?
Move the setup code to helper methods defined in spec_helper.rb or in a spec/support/{something}.rb file.
–