diff --git a/app/models/poll.rb b/app/models/poll.rb index 9087b64d0..abaaf5d2d 100644 --- a/app/models/poll.rb +++ b/app/models/poll.rb @@ -39,6 +39,7 @@ class Poll < ApplicationRecord validate :date_range validate :start_date_is_not_past_date, on: :create validate :start_date_change, on: :update + validate :end_date_is_not_past_date, on: :update validate :only_one_active, unless: :public? accepts_nested_attributes_for :questions, reject_if: :all_blank, allow_destroy: true @@ -161,6 +162,12 @@ class Poll < ApplicationRecord end end + def end_date_is_not_past_date + if will_save_change_to_ends_at? && ends_at < Time.current + errors.add(:ends_at, I18n.t("errors.messages.past_date")) + end + end + def generate_slug? slug.nil? end diff --git a/spec/models/poll/poll_spec.rb b/spec/models/poll/poll_spec.rb index daa30aca1..ca79d47ff 100644 --- a/spec/models/poll/poll_spec.rb +++ b/spec/models/poll/poll_spec.rb @@ -69,6 +69,18 @@ describe Poll do poll.starts_at = 10.days.from_now expect(poll).not_to be_valid end + + it "is valid if changing the end date to a future date" do + poll.ends_at = 1.day.from_now + expect(poll).to be_valid + end + + it "is not valid if changing the end date to a past date" do + poll = create(:poll, starts_at: 10.days.ago, ends_at: 10.days.from_now) + + poll.ends_at = 1.day.ago + expect(poll).not_to be_valid + end end end