测试控制器问题(在Rails 3.2中)

时间:2013-08-27 22:51:01

标签: ruby-on-rails rspec activesupport

我为管理名为'record_search'的记录创建了一个内部gem,其中包含一个名为'ApiController'的控制器。在一个应用程序中,我需要挂钩授权行为以防止数据被公开访问,所以我添加了一个ActiveSupport :: Concern模块允许应用添加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

本地应用:

应用/控制器/关切/ 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

1 个答案:

答案 0 :(得分:0)

假设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

与高级用户的可比较示例。另请参阅http://apidock.com/rails/ActionController/Assertions/ResponseAssertions/assert_response,尽管我不熟悉使用Rails的断言。

顺便说一下,实际的require_premium_user代码对我来说没有意义。