【问题标题】:Testing Controller Concerns (in Rails 3.2)测试控制器问题(在 Rails 3.2 中)
【发布时间】:2013-08-27 22:51:01
【问题描述】:

我创建了一个内部 gem 用于管理名为“record_search”的记录,其中包括一个名为“ApiController”的控制器。在一个应用程序中,我需要挂钩授权行为以防止数据被公开访问,因此我添加了一个ActiveSupport::Concern 模块允许应用添加 before_filter。如何正确测试此 before_filter? (使用 rspec)

在宝石中:

app/controllers/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

【问题讨论】:

    标签: ruby-on-rails rspec activesupport


    【解决方案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
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多