Rspec Rails - 测试before_filter无效的结果

时间:2018-06-05 13:51:30

标签: ruby-on-rails rspec rspec-rails contentful

我正在使用Contentful Model从Contentful中获取CMS类型的内容,并使用Rails应用程序进行显示。如果ContentfulModel.use_preview_api设置为true,则Contentful Model将查询预览API,而不是主API,从而允许预览未发布的内容。

我在控制器中编写了一些逻辑来检查是否存在有效的预览密钥集,如果是,则将ContentfulModel.use_preview_api设置为true。这一切都在开发中工作,但当我来为它编写测试时,他们坚决拒绝通过。这是我的控制器:

class BlogPostsController < ApplicationController
  caches_action :index, :show, skip_digest: true, unless: -> { preview_enabled? }
  before_action :check_preview, only: :show

  def index
    @blog_posts = BlogPost.all.load
  end

  def show
    @blog_post = BlogPost.find_by(slug: params[:id]).load.first
  end

  private

  def preview_enabled?
    params[:preview_token] == ENV['PREVIEW_TOKEN']
  end

  def check_preview
    ContentfulModel.use_preview_api = preview_enabled?
  end
end

这是我的测试:

require 'rails_helper'

RSpec.describe BlogPostsController, type: :controller, vcr: true do
  describe 'uses the preview API' do
    let(:subject) { get :show, params: { id: 'wanted-pioneer-partners-for-the-what-works-centre', preview_token: ENV['PREVIEW_TOKEN'] } }

    it 'when the token is set correctly' do
      subject
      expect(a_request(:get, /preview.contentful.com/)).to have_been_made.at_least_once
    end
  end
end

(我正在使用WebMock测试请求是否发送到Contentful的预览API,而不是主API(即cdn.contentful.com))

当我运行测试时,我收到以下错误:

1) BlogPostsController uses the preview API when the token is set correctly
   Failure/Error: expect(a_request(:get, /preview.contentful.com/)).to have_been_made.at_least_once

     The request GET /preview.contentful.com/ was expected to execute at least 1 time but it executed 0 times

     The following requests were made:

     GET https://cdn.contentful.com/spaces/xxxxx/environments/master/content_types?limit=1000 with headers {'Accept-Encoding'=>'gzip', 'Authorization'=>'Bearer xxxxx', 'Connection'=>'close', 'Content-Type'=>'application/vnd.contentful.delivery.v1+json', 'Host'=>'cdn.contentful.com', 'User-Agent'=>'http.rb/2.2.2', 'X-Contentful-User-Agent'=>'sdk contentful.rb/2.8.0; integration contentful_model/1.0.0; platform ruby/2.5.0; os macOS/17;'} was made 1 time
     GET https://cdn.contentful.com/spaces/xxxxx/environments/master/entries?content_type=blogPost&fields.slug=wanted-pioneer-partners-for-the-what-works-centre&include=2 with headers {'Accept-Encoding'=>'gzip', 'Authorization'=>'Bearer xxxxx', 'Connection'=>'close', 'Content-Type'=>'application/vnd.contentful.delivery.v1+json', 'Host'=>'cdn.contentful.com', 'User-Agent'=>'http.rb/2.2.2', 'X-Contentful-User-Agent'=>'sdk contentful.rb/2.8.0; integration contentful_model/1.0.0; platform ruby/2.5.0; os macOS/17;'} was made 1 time

     ============================================================

这表明预览API没有被点击。

关于我可能出错的地方的任何想法?我认为这很可能是一个rspec-rails问题,而不是特定内容。

0 个答案:

没有答案