Permalink
Browse files

Use BCrypt's MIN_COST in the test environment for speedier tests

  • Loading branch information...
1 parent 087150d commit 06faa6da808ef9e98455c35aefd4a4112c811c8f @trevorturk trevorturk committed Nov 14, 2012
View
@@ -1,5 +1,9 @@
## Rails 4.0.0 (unreleased) ##
+* Use BCrypt's MIN_COST in the test environment for speedier tests when using `has_secure_pasword`.
+
+ *Brian Cardarella + Jeremy Kemper + Trevor Turk*
+
* Add `ActiveModel::ForbiddenAttributesProtection`, a simple module to
protect attributes from mass assignment when non-permitted attributes are passed.
@@ -4,5 +4,9 @@
module ActiveModel
class Railtie < Rails::Railtie # :nodoc:
config.eager_load_namespaces << ActiveModel
+
+ initializer "active_model.secure_password" do
+ ActiveModel::SecurePassword.min_cost = Rails.env.test?
+ end
end
end
@@ -2,6 +2,8 @@ module ActiveModel
module SecurePassword
extend ActiveSupport::Concern
+ class << self; attr_accessor :min_cost; end
+
module ClassMethods
# Adds methods to set and authenticate against a BCrypt password.
# This mechanism requires you to have a password_digest attribute.
@@ -88,7 +90,8 @@ def authenticate(unencrypted_password)
def password=(unencrypted_password)
unless unencrypted_password.blank?
@password = unencrypted_password
- self.password_digest = BCrypt::Password.create(unencrypted_password)
+ cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine::DEFAULT_COST
+ self.password_digest = BCrypt::Password.create(unencrypted_password, cost: cost)
end
end
end
@@ -0,0 +1,28 @@
+require 'cases/helper'
+require 'active_support/testing/isolation'
+
+class RailtieTest < ActiveModel::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ require 'rails/all'
+
+ @app ||= Class.new(::Rails::Application).tap do |app|
+ app.config.eager_load = false
+ end
+ end
+
+ test 'secure password min_cost is false in the development environment' do
+ Rails.env = 'development'
+ @app.initialize!
+
+ assert_equal false, ActiveModel::SecurePassword.min_cost
+ end
+
+ test 'secure password min_cost is true in the test environment' do
+ Rails.env = 'test'
+ @app.initialize!
+
+ assert_equal true, ActiveModel::SecurePassword.min_cost
+ end
+end
@@ -63,10 +63,21 @@ class SecurePasswordTest < ActiveModel::TestCase
@user.run_callbacks :create
end
end
-
+
test "Oauthed user can be created with blank digest" do
assert_nothing_raised do
@oauthed_user.run_callbacks :create
end
end
+
+ test "Password digest cost defaults to bcrypt default cost" do
+ @user.password = "secret"
+ assert_equal BCrypt::Engine::DEFAULT_COST, @user.password_digest.cost
+ end
+
+ test "Password digest cost can be set to bcrypt min cost to speed up tests" do
+ ActiveModel::SecurePassword.min_cost = true
+ @user.password = "secret"
+ assert_equal BCrypt::Engine::MIN_COST, @user.password_digest.cost
+ end
end

1 comment on commit 06faa6d

Please sign in to comment.