functional tests with machinist and authlogic
Authlogic and Machinist are two libraries that are a great help in getting a Rails app up and running quickly. But once we had a prototype running and some solid unit tests going, I ran into a snag. How do I create
The Machinist
Users and UserSessions in a way that agrees with AuthLogic so that my requires_user before filter is working properly within a functional test?
The Machinist
test_case.rb has some good explanation, but they focus on fixtures and leave out some easy steps.
Here's how I setup my functional tests:
In test_helper.rb I added a login() method :
def login(u = nil)
user = User.make(u)
assert UserSession.create(user)
user
end
In blueprints.rb, i added the fields that AuthLogic needs to authenticate a user:
User.blueprint do
email { "testuser@company.biz" }
password { "test" }
password_confirmation { password }
#this is all needed so we can log in for functional tests
password_salt {Authlogic::Random.hex_token }
crypted_password { Authlogic::CryptoProviders::Sha512.encrypt(password + password_salt) }
persistence_token { Authlogic::Random.hex_token }
single_access_token { Authlogic::Random.friendly_token }
perishable_token { Authlogic::Random.friendly_token }
active { true }
end
Finally, in the functional tests, you can simply use login() to simulate a session within the functional test:
test "should force login" do
get :index
assert_redirects_to login_path
end
test "should get index" do
login
get :index
assert_response :success
assert_not_nil assigns(:items)
end
I hope this helps. If you have any suggestions or improvements, please leave a comment.
Trackbacks
Use the following link to trackback from your own site:
http://www.kudelabs.com/trackbacks?article_id=115
