2

「ApiController」という名前のコントローラーを含む、「record_search」というレコード管理用の社内ジェムを作成しました。あるアプリでは、データが公開されないようにするために認証動作をフックする必要があったため、ActiveSupport:: を追加しました。アプリが before_filter を追加できるようにする懸念モジュール。この before_filter を適切にテストするにはどうすればよいですか? (rspec を使用)

ジェムで:

アプリ/コントローラー/api_controller.rb

module RecordSearch
  class ApiController < ApplicationController
    respond_to :json

    def search
      render json: #app-specific code
    end

    def find
      render json: #app-specific code
    end

    include Extensions #define any authorization logic here
  end
end

ローカル アプリ:

app/controllers/concerns/record_search/extensions.rb

module RecordSearch::Extensions
  extend ActiveSupport::Concern
  include ApplicationHelper #defines current_user method

  included do
    before_filter :require_premium_user, :only => [:find,:search]
  end

  private

  def require_premium_user
    unless current_user
      return render :json => {"error" => "not authorized"}
    end
  end
end
4

1 に答える 1

1

が現在のテスト対象のコントローラーであると仮定するcontrollerと、次を使用できます。

describe "searching when not a premimum user" do
   let(:user) { ... } # code to create a regular user
   before { ... } # code to login user
   it "should return an error message" do
      expect(controller).to receive(:render).with({"error" => "not authorized"})
      # code to trigger find or search
   end
end

プレミアムユーザー向けの比較例を示します。Rails のアサーションの使用に慣れていませんが、http://apidock.com/rails/ActionController/Assertions/ResponseAssertions/assert_responseも参照してください。

余談ですが、実際のrequire_premium_userコードは私には意味がありませんでした。

于 2013-08-28T14:07:58.047 に答える