我的Rails4应用程序中有一个小型REST API。基本上它是一个有7个动作的控制器。只有经过身份验证的用户才允许访问API,并且从Devise gem中添加了与before_filter相同的检查。测试这一点的最佳方法是什么?
我已经为API进行了单元测试,如果每个操作需要身份验证,我会手动测试它,但我显然不喜欢这样。
在RSpec中,您可以使用共享示例:
# 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