我的Rails 4应用程序中有一个小的REST API。基本上它是一个有7个动作的控制器。只有经过身份验证的用户才能访问API,并且检查是从Devise gem添加为before_filter的。测试这个的最佳方法是什么?
我已经对API进行了单元测试,如果需要身份验证,我会手动测试每个操作,但我显然不喜欢这样。
答案 0 :(得分:4)
在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