tests: add normalize_attribute helper method.

Add a custom Shoulda matcher for testing that a model correctly normalizes an attribute.

Usage:

    subject { build(:wiki_page) }
    should normalize_attribute(:title).from(" Azur  Lane ").to("azur_lane")
This commit is contained in:
evazion
2021-01-09 18:40:21 -06:00
parent 9759701071
commit ff6e640fcb
3 changed files with 53 additions and 8 deletions

View File

@@ -27,6 +27,7 @@ class ActiveSupport::TestCase
include IqdbTestHelper
include UploadTestHelper
extend StripeTestHelper
extend NormalizeAttributeHelper
mock_post_version_service!
mock_pool_version_service!

View File

@@ -0,0 +1,45 @@
# A custom Shoulda matcher for testing that a model correctly normalizes an attribute.
#
# Usage:
#
# subject { build(:wiki_page) }
# should normalize_attribute(:title).from(" Azur Lane ").to("azur_lane")
#
# https://thoughtbot.com/blog/shoulda-matchers
module NormalizeAttributeHelper
def normalize_attribute(attribute)
NormalizeAttributeMatcher.new(attribute)
end
class NormalizeAttributeMatcher
attr_reader :attribute, :from_value, :to_value
def initialize(attribute)
@attribute = attribute
end
def matches?(subject)
subject.send("#{attribute}=", from_value)
subject.send(attribute) == to_value
end
def description
"normalize the `#{attribute}` attribute from `#{from_value}` to `#{to_value}`"
end
def failure_message
"expected `#{attribute}=` to normalize `#{from_value}` to `#{to_value}`"
end
def from(from_value)
@from_value = from_value
self
end
def to(to_value)
@to_value = to_value
self
end
end
end

View File

@@ -92,14 +92,13 @@ class WikiPageTest < ActiveSupport::TestCase
end
context "during title validation" do
# these values are allowed because they're normalized first
should allow_value(" foo ").for(:title).on(:create)
should allow_value("~foo").for(:title).on(:create)
should allow_value("_foo").for(:title).on(:create)
should allow_value("foo_").for(:title).on(:create)
should allow_value("foo__bar").for(:title).on(:create)
should allow_value("FOO").for(:title).on(:create)
should allow_value("foo bar").for(:title).on(:create)
should normalize_attribute(:title).from(" foo ").to("foo")
should normalize_attribute(:title).from("~foo").to("foo")
should normalize_attribute(:title).from("_foo").to("foo")
should normalize_attribute(:title).from("foo_").to("foo")
should normalize_attribute(:title).from("FOO").to("foo")
should normalize_attribute(:title).from("foo__bar").to("foo_bar")
should normalize_attribute(:title).from("foo bar").to("foo_bar")
should_not allow_value("").for(:title).on(:create)
should_not allow_value("___").for(:title).on(:create)