FIX: Compute number of pages correctly (#19)

FIX: Compute number of pages correctly (#19)

There were multiple off-by-one errors which counted as two pages of 20 posts even when there were only 19 posts.

diff --git a/app/views/discourse_sitemap/sitemap/default.erb b/app/views/discourse_sitemap/sitemap/default.erb
index 9d96cd1..c95297d 100644
--- a/app/views/discourse_sitemap/sitemap/default.erb
+++ b/app/views/discourse_sitemap/sitemap/default.erb
@@ -11,10 +11,9 @@
     <%-
         url = "#{Discourse.base_url}/t/#{topic[1]}/#{topic[0]}"
         if topic[4]
-          page = ((topic[4]+1) / TopicView.chunk_size) + 1
-          if page > 1
-            url += "?page=#{page}"
-          end
+          page = topic[4] / TopicView.chunk_size
+          page += 1 if topic[4] % TopicView.chunk_size > 0
+          url += "?page=#{page}" if page > 1
         end
     -%>
         <loc><%= url %></loc>
diff --git a/spec/requests/sitemap_controller_spec.rb b/spec/requests/sitemap_controller_spec.rb
index fc58d74..ec58757 100644
--- a/spec/requests/sitemap_controller_spec.rb
+++ b/spec/requests/sitemap_controller_spec.rb
@@ -25,5 +25,41 @@ RSpec.describe DiscourseSitemap::SitemapController do
 
       expect(response.status).to eq(200)
     end
+
+    it 'generates correct page numbers' do
+      topic = Fabricate(:topic)
+
+      # 18 posts - one incomplete page
+
+      (1..TopicView.chunk_size - 2).each { |idx| Fabricate(:post, topic: topic) }
+      topic.update!(bumped_at: 4.hour.ago)
+      get '/sitemap_recent.xml'
+      url = Nokogiri::XML::Document.parse(response.body).at_css('loc').text
+      expect(url).not_to include('?page=2')
+
+      # 19 posts - still one incomplete page
+
+      Fabricate(:post, topic: topic)
+      topic.update!(bumped_at: 3.hour.ago)
+      get '/sitemap_recent.xml'
+      url = Nokogiri::XML::Document.parse(response.body).at_css('loc').text
+      expect(url).not_to include('?page=2')
+
+      # 20 posts - one complete page
+
+      Fabricate(:post, topic: topic)
+      topic.update!(bumped_at: 2.hour.ago)
+      get '/sitemap_recent.xml'
+      url = Nokogiri::XML::Document.parse(response.body).at_css('loc').text
+      expect(url).not_to include('?page=2')
+
+      # 21 posts - two pages - one complete page and one incomplete page
+
+      Fabricate(:post, topic: topic)
+      topic.update!(bumped_at: 1.hour.ago)
+      get '/sitemap_recent.xml'
+      url = Nokogiri::XML::Document.parse(response.body).at_css('loc').text
+      expect(url).to include('?page=2')
+    end
   end
 end

GitHub sha: 3093b4d1

This commit appears in #19 which was approved by ZogStriP. It was merged by nbianca.