Skip to content

Instantly share code, notes, and snippets.

@frank184
Last active September 21, 2016 23:38
Show Gist options
  • Save frank184/38ccaa4f23ffc0d2eb77aeb1a4387063 to your computer and use it in GitHub Desktop.
Save frank184/38ccaa4f23ffc0d2eb77aeb1a4387063 to your computer and use it in GitHub Desktop.
HasSecureToken extension for shoulda-matchers gem while using has_secure_token gem
# config/application.rb
module YourApp
class Application < Rails::Application
# ...
# Auto load lib folder
config.autoload_paths << Rails.root.join('lib')
end
end
# lib/shoulda/matchers/active_model/have_secure_token.rb
module Shoulda
module Matchers
module ActiveModel
def have_secure_token(attr)
HaveSecureTokenMatcher.new(attr)
end
# @private
class HaveSecureTokenMatcher
attr_reader :failure_message
EXPECTED_METHODS = [
:regenerate_token,
]
MESSAGES = {
method_not_found: "expected %{subject} to respond to %{methods}",
did_not_persist_record: "expected %{subject} to be persisted to the database",
did_not_save_with_secure_token: "expected %{subject} to save and with a secure %{attribute}",
}
def initialize(attribute)
@attribute = attribute.to_sym
end
def description
"have a secure #{attribute}"
end
def matches?(subject)
@subject = subject
if failure = validate
key, params = failure
@failure_message = MESSAGES[key] % { subject: subject.class }.merge(params)
end
failure.nil?
end
protected
attr_reader :subject, :attribute
def validate
EXPECTED_METHODS << attribute
missing_methods = EXPECTED_METHODS.select {|m| !subject.respond_to?(m) }
if missing_methods.present?
[:method_not_found, { methods: missing_methods.to_sentence }]
else
subject.send("#{attribute}=", nil)
subject.regenerate_token
if subject.changed?
[:did_not_persist_record, {}]
end
if subject.send(attribute).nil?
[:did_not_save_with_secure_token, { attribute: attribute }]
end
end
end
end
end
end
end
# config/initializers/shoulda-matchers.rb
require 'shoulda/matchers/active_model/have_secure_token_matcher'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment