Skip to content

Commit

Permalink
Adding feature limit class attribute (#6680)
Browse files Browse the repository at this point in the history
* Adding feature limit class attribute

* 🐛 Fix subject of spec
  • Loading branch information
jeremyf authored Feb 8, 2024
1 parent 453bf83 commit 5fbf679
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
16 changes: 12 additions & 4 deletions app/models/featured_work.rb
Original file line number Diff line number Diff line change
@@ -1,21 +1,29 @@
# frozen_string_literal: true
class FeaturedWork < ActiveRecord::Base
FEATURE_LIMIT = 5
##
# @!group Class Attributes
#
# @!attribute feature_limit [r|w]
# @return [Integer]
class_attribute :feature_limit, default: 5
# @!endgroup Class Attributes
##

validate :count_within_limit, on: :create
validates :order, inclusion: { in: proc { 0..FEATURE_LIMIT } }
validates :order, inclusion: { in: proc { 0..feature_limit } }

default_scope { order(:order) }

def count_within_limit
return if FeaturedWork.can_create_another?
errors.add(:base, "Limited to #{FEATURE_LIMIT} featured works.")
errors.add(:base, "Limited to #{feature_limit} featured works.")
end

attr_accessor :presenter

class << self
def can_create_another?
FeaturedWork.count < FEATURE_LIMIT
FeaturedWork.count < feature_limit
end
end
end
12 changes: 9 additions & 3 deletions spec/models/featured_work_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,23 @@
RSpec.describe FeaturedWork, type: :model do
let(:feature) { described_class.create(work_id: "99") }

describe '.feature_limit' do
subject { described_class.feature_limit }

it { is_expected.to be_a(Integer) }
end

it "has a file" do
expect(feature.work_id).to eq "99"
end

it "does not allow six features" do
5.times do |n|
described_class.feature_limit.times do |n|
expect(described_class.create(work_id: n.to_s)).not_to be_new_record
end
described_class.create(work_id: "6").tap do |sixth|
expect(sixth).to be_new_record
expect(sixth.errors.full_messages).to eq ["Limited to 5 featured works."]
expect(sixth.errors.full_messages).to eq ["Limited to #{described_class.feature_limit} featured works."]
end
expect(described_class.count).to eq 5
end
Expand All @@ -29,7 +35,7 @@
end
context "when five exist" do
before do
5.times do |n|
described_class.feature_limit.times do |n|
described_class.create(work_id: n.to_s)
end
end
Expand Down

0 comments on commit 5fbf679

Please sign in to comment.