Reputation: 1
I am somewhat new to Rails 4 and am working on a project that requires authentication. I have recently implemented Authlogic to handle it.
The problem is a specific test for the session controller where I try to log in using HTTP post, which fails redirecting me to the login path. I am interested in this because it will probably be used later to log an Android application using the users in my Rails app.
This is the test:
sessions_controller_test.rb
test "should post create" do
this_user = users(:one)
post :create, username: this_user.username, password: 'secret'
assert_redirected_to admin_url
assert_equal this_user.id, current_user.id #session[:user_id]
end
This is the code being tested:
sessions_controller.rb
def create
@user_session = Session.new(params[:user_session])
if @user_session.save
flash[:notice] = "Login successful."
redirect_to admin_url
else
redirect_to login_url, alert: "Invalid user/password combination"
end
end
And the test result:
2) Failure:
SessionsControllerTest#test_should_post_create [/home/mario/railsprj/depot/test/controllers/sessions_controller_test.rb:13]:
Expected response to be a redirect to <http://test.host/admin> but was a redirect to <http://test.host/login>.
Expected "http://test.host/admin" to be === "http://test.host/login".
Thanks in advance.
Upvotes: 0
Views: 525
Reputation: 11
Hope it is not too late for the answer. The problem in your code is that you are missing the params.
You have to change the test:
test "should post create" do
this_user = users(:one)
post :create, user_session: { username: this_user.username, password:
'secret'}
Or you have to change the controller:
sessions_controller.rb
def create
@user_session = Session.new(username: params[:username], password: params[:password])
Only one of both choices. I think is better the first solution, but is a kind of taste.
Regards
Roberto
Upvotes: 1
Reputation: 722
I experienced a similar issue. Check @user_session.errors
in the else branch of your session_controller#create. Or switch to @user_session.save!
temporarily to throw an error if validation is wrong. In my case a validation related to user.confirmed_at was failing.
The other thing to check is that your test has setup :activate_authlogic
which is required before you can Session.create.
Upvotes: 1