diff --git a/test/test_helper.rb b/test/test_helper.rb index ca6a4b4f2..65462e850 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -27,6 +27,7 @@ class ActiveSupport::TestCase include IqdbTestHelper include UploadTestHelper extend StripeTestHelper + extend NormalizeAttributeHelper mock_post_version_service! mock_pool_version_service! diff --git a/test/test_helpers/normalize_attribute_helper.rb b/test/test_helpers/normalize_attribute_helper.rb new file mode 100644 index 000000000..610ee59f0 --- /dev/null +++ b/test/test_helpers/normalize_attribute_helper.rb @@ -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 diff --git a/test/unit/wiki_page_test.rb b/test/unit/wiki_page_test.rb index 150561e3b..0ed9ca5a3 100644 --- a/test/unit/wiki_page_test.rb +++ b/test/unit/wiki_page_test.rb @@ -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)