【问题标题】:Testing that all actions in a controller allow only authenticated users测试控制器中的所有操作是否只允许经过身份验证的用户
【发布时间】:2015-12-09 20:31:47
【问题描述】:

我的 Rails 4 应用中有一个小型 REST API。基本上它是一个有 7 个动作的控制器。只有经过身份验证的用户才能访问 API,并且从 Devise gem 中添加了检查作为 before_filter。对此进行测试的最佳方法是什么?

我已经对 API 进行了单元测试,如果需要身份验证,我会手动测试每个操作,但我显然不喜欢这样。

【问题讨论】:

  • 使用 minitest、test-unit 还是 rspec?
  • @max 我使用 rspec,但我正在寻找如何删除样板代码的一般想法。我会很感激任何例子

标签: ruby-on-rails unit-testing


【解决方案1】:

在 RSpec 中你可以use shared examples:

# spec/support/shared_examples/authentication.rb
RSpec.shared_examples "an authenticated action" do |action|
  it "requires authentication" do
    expect { action.call }.to raise_exception("uncaught throw :warden")
  end
end

require 'rails_helper'
require 'support/shared_examples/authentication'

RSpec.describe PetsController do
  describe "GET #index" do
   it_behaves_like "an authenticated action", { get :index }
  end
  describe "PATCH #update" do
   it_behaves_like "an authenticated action", { patch :update, { pet: { name: 'Moon Moon' }} }
  end
  describe "DELETE #destroy" do
   it_behaves_like "an authenticated action", { delete :destroy, id: 1 }
  end
end

【讨论】:

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