diff --git a/app/models/topic.rb b/app/models/topic.rb index 3d85a00..ba0ddbb 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -47,6 +47,10 @@ class Topic < ActiveRecord::Base acts_as_readable + def self.recent_topics + Post.order('id desc').select('DISTINCT topic_id').limit(5).map(&:topic) + end + def to_s title end diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rb index 5cd81d1..536c50b 100644 --- a/spec/models/topic_spec.rb +++ b/spec/models/topic_spec.rb @@ -27,4 +27,20 @@ describe Topic do end.to change(Topic, :count).by(1) end end + + describe ".recent_topics" do + before(:all) do + 5.times do + topic = create :topic + 3.times do + post = create :post, topic: topic + end + end + end + it "returns 5 unique, most recently posted topics" do + recent_topics = Topic.recent_topics + expect(recent_topics.length).to eq(5) + expect(recent_topics.map(&:id).uniq.length).to eq(5) + end + end end