diff --git a/spec/example_app/app/models/product.rb b/spec/example_app/app/models/product.rb index 64e11b4154..7dc567611c 100644 --- a/spec/example_app/app/models/product.rb +++ b/spec/example_app/app/models/product.rb @@ -11,8 +11,10 @@ def self.policy_class has_many :pages, dependent: :destroy has_one :product_meta_tag, dependent: :destroy + before_validation :trim_image_url + validates :description, presence: true - validates :image_url, presence: true + validates :image_url, presence: true, format: %r{\Ahttps?://} validates :name, presence: true validates :price, presence: true validates :release_year, @@ -40,4 +42,10 @@ def valid_slug errors.add :name, "must have letters or numbers for the URL" end end + + private + + def trim_image_url + image_url&.strip! + end end diff --git a/spec/example_app/spec/models/product_spec.rb b/spec/example_app/spec/models/product_spec.rb new file mode 100644 index 0000000000..2818f24069 --- /dev/null +++ b/spec/example_app/spec/models/product_spec.rb @@ -0,0 +1,19 @@ +require "rails_helper" + +RSpec.describe Product do + describe "validations" do + it { should allow_value("http://example.com/foo/bar").for(:image_url) } + it { should allow_value("https://example.com/foo/bar").for(:image_url) } + it { should_not allow_value("ftp://example.com/foo/bar").for(:image_url) } + end + + describe "#image_url" do + it "is trimmed on save" do + product = FactoryBot.create( + :product, + image_url: "\n https://example.com/foo/bar \n", + ) + expect(product.image_url).to eq("https://example.com/foo/bar") + end + end +end