RSpec doesn't use cache

Viewed 20

I'm playing around with RSpec to make sure caching is properly working.

I have a simple controller

module Api::V1
  class ArticlesController < Api::V1::BaseController
    def index
      @articles = Rails.cache.fetch(Article.cache_key) do
        p "IT IS A MISS" # Added for debugging
        Article.all
      end
    end
  end
end

and the spec below

RSpec.describe Api::V1::ArticlesController, type: :request do
...

  it 'cache?', :caching do
    create_list(:article, 2)
    get '/api/v1/articles.json'
    expect(JSON.parse(response.body).size).to eq(2)
    create(:article)
    get '/api/v1/articles.json'
    expect(JSON.parse(response.body).size).to eq(2)
  end
end

with the following configuration

RSpec.configure do |config|
  config.around(:each, :caching) do |example|
    Rails.cache.clear
    caching = ActionController::Base.perform_caching
    ActionController::Base.perform_caching = example.metadata[:caching]
    example.run
    ActionController::Base.perform_caching = caching
  end
end

To make the spec pass and insure the cache is a hit I have defined cache_key as follows

def self.cache_key
  'articles'
end

However, even if the cache is a miss only for the first request, the spec fails.

% RUBYOPT="-W0" bin/rspec spec/requests/api/v1/articles_controller_spec.rb:35
"IT IS A MISS"
F

Failures:

  1) Api::V1::ArticlesController cache? is expected to eq 2
     Failure/Error: expect(JSON.parse(response.body).size).to eq(2)

       expected: 2
            got: 3

       (compared using ==)
     # ./spec/requests/api/v1/articles_controller_spec.rb:39:in `block (4 levels) in <top (required)>'
     # ./spec/support/config/capybara.rb:21:in `block (2 levels) in <main>'

Am I missing anything here?

0 Answers
Related