On my website each user can have the following roles:
-
Not logged in
-
Logged in
- active
- administrator
- sysadministrator
How would you write DRY specs to test each action of a controller?
Currently I am doing somethings that looks like:
describe ‘a non admin is signed in’, :shared => true do
before(:each) do
@current_user = mock_model(User, :id => 1, :state => ‘active’)
controller.stub!(:current_user).and_return(@current_user)
@current_user.should_receive(:administrator?).and_return(false)
@current_user.should_receive(:sysadministrator?).and_return(false)
end
end
describe ‘an administrator is signed in’, :shared => true do
before(:each) do
@current_user = mock_model(User, :id => 1, :state =>
‘administrator’)
controller.stub!(:current_user).and_return(@current_user)
@current_user.should_receive(:administrator?).and_return(true)
end
end
describe Admin::OrdersController, ‘index’ do
describe “A non admin wants to have access” do
it_should_behave_like ‘a non admin is signed in’
it "should redirect" do
get :index
response.should redirect_to(products_url)
end
end
describe “An admin wants to have access” do
it_should_behave_like ‘an administrator is signed in’
it "should render index page" do
controller.should_receive(:select_date_initializer).with({},nil)
Order.should_not_receive(:admin_find_from_params)
get :index
end
it "should accept search params on index page" do
Order.should_receive(:admin_find_from_params).with('test.host',
{}, {})
get :index, :commit => 'Search'
end
end
end # describe Admin::OrdersController, ‘index’
I didn’t test for the sysadministrator as it would force me to repeat
all the tests for administrator, basically a sysadministrator has
administrator rights and more. What is a better way of writing such
specs?