Ruby on Rails functional test with Devise authentication

萝らか妹 提交于 2019-12-03 02:58:41

Are you using Devise with confirmable? In this case, create is not enough and you need to confirm the user with @user.confirm!

Second, why do you create the user in the functional test? Declare your users in the fixture like this (confirmed_at if you require confirmation only):

test/fixtures/users.yml:

user1: 
id: 1
email: user1@test.eu
encrypted_password: abcdef1
password_salt:  efvfvffdv
confirmed_at: <%= Time.now %>

and sign them in in your functional tests with:

sign_in users(:user1)

Edit: I just saw, that in my app the Devise-Testhelpers are declared in test/test-helpers.rb and I don't know if this makes a difference, maybe you want to try:

ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActionController::TestCase
  include Devise::TestHelpers
end

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
  #
  # Note: You'll currently still have to declare fixtures explicitly in integration tests
  # -- they do not yet inherit this setting
  fixtures :all

  # Add more helper methods to be used by all tests here...
end

This took me some time to figure out but it turns out the answer is really simple.

The point is that, in your fixtures file (users.yml), you need to make sure the user is 'confirmed' (assuming that you specified "confirmable" in your User model). So, for instance, put this in your users.yml:

user_one:
  confirmed_at: 2015/01/01

That's all, no need to specify other fields (email, encrypted password, etc).

Now in your controller test (e.g. in 'setup' or in 'before') you simply code:

sign_in users(:user_one)

And then it should just work!

I had a similar issue (but using FactoryGirl, rather than Fixtures) and was able to resolve it by simply using FactoryGirl.create(:user) rather than FactoryGirl.build(:user).

Evidently, Devise requires the user to have been persisted to the Database, for everything to work properly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!