In rails I have a before_filter that checks and requires that the user is an admin for certain actions in the controller.
However, I need to write tests for these controllers.
So, I have something that looks like this:
test "should get create" do
assert_difference('Event.count') do
post :create, FactoryGirl.build(:event)
end
assert_not_nil assigns(:event)
assert_response :success
end
user_factory.rb:
FactoryGirl.define do
factory :admin do
email 'aa@example.com'
password 'password'
password_confirmation 'password'
admin true
end
end
But need to login as an admin to be able to create the event. Any ideas on how to do this? The admin column is just a true/false column in the users table.
Edit: First Attempt:
test "should get create" do
admin = Factory(:admin)
login_as(admin)
assert_difference('Event.count') do
post :create, FactoryGirl.build(:event)
end
assert_not_nil assigns(:event)
assert_response :success
end
generates error:
1) Error:
test_should_get_create(EventsControllerTest):
NameError: uninitialized constant Admin
Update:
FactoryGirl.define do
factory :user do
email 'aa@example.com'
password 'password'
password_confirmation 'password'
end
end
and
test "should get create" do
login_as(FactoryGirl.create(:user, admin: true))
assert_difference('Event.count') do
post :create, FactoryGirl.build(:event)
end
assert_not_nil assigns(:event)
assert_response :success
end
and I get the error test_should_get_create(EventsControllerTest):
NoMethodError: undefined method 'login_as' for #<EventsControllerTest:0x007fb4faec1b28>
When you define your
factory(:admin), FactoryGirl looks for a class calledAdmin, which is why you’re getting that error.You don’t need to create a separate factory for
admin; you can simply use your User factory, passing inadmin: true(that’ll override the default factory settings). So doadmin = Factory(:user, admin: true). Make sure you have theuserfactory defined of course.If you want to keep the
:adminfactory, you need to specify that the class isUser. The syntax goes something like this:factory(:admin, class: "User").