Last active
September 21, 2016 23:38
-
-
Save frank184/38ccaa4f23ffc0d2eb77aeb1a4387063 to your computer and use it in GitHub Desktop.
HasSecureToken extension for shoulda-matchers gem while using has_secure_token gem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/application.rb | |
module YourApp | |
class Application < Rails::Application | |
# ... | |
# Auto load lib folder | |
config.autoload_paths << Rails.root.join('lib') | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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