【发布时间】:2015-08-03 12:34:40
【问题描述】:
我正在构建一个 Rails API,目前正在使用门卫,并设计使用 ResourceOwnerFromCredentials 流对用户进行身份验证。一切正常,但是,我无法在 Rspec 中进行身份验证。
这是在 rspec 中集成应用程序的方式:
let(:app_country) { FactoryGirl.create(:app_country)}
let(:valid_attributes) { FactoryGirl.attributes_for(:app_city, {:app_country_id => app_country.id}) }
let(:valid_session) { {:format => :json} }
let(:application) { Doorkeeper::Application.create!(:name => "App HQ dashboard", :redirect_uri => "https://localhost:3000/callback") }
let(:hq_user) { app_country.hq_users.create!(FactoryGirl.attributes_for :hq_user) }
let(:token) { Doorkeeper::AccessToken.create! :application_id => application.id, :resource_owner_id => hq_user.id }
但每次我尝试测试受保护的操作时,测试都会失败,并且我会从控制台获得以下输出:
Filter chain halted as :doorkeeper_authorize! rendered or redirected
Completed 403 Forbidden in 5ms (ActiveRecord: 1.2ms)
这在以前版本的门卫上运行良好。当我升级门卫 gem 时,测试中断了。我究竟做错了什么?或者有没有一种测试门卫保护控制器的新方法?
更新
下面是一个实际的测试样本
describe "POST create" do
describe "with valid params" do
it "creates a new AppCity" do
expect {
post :create, {:app_city => valid_attributes, :v => "HEAD", :payload_type => "NODE", :access_token => token.token}, valid_session
}.to change(AppCity, :count).by(1)
end
it "persists the AppCity" do
post :create, {:app_city => valid_attributes, :v => "HEAD", :access_token => token.token}, valid_session
response_body = JSON.parse(response.body, symbolize_names: true)
expect(response_body[:id]).to be_present
end
it "returns a 201 status" do
post :create, {:app_city => valid_attributes, :v => "HEAD", :access_token => token.token}, valid_session
response.status.should eq(201)
end
end
describe "with invalid params" do
it "returns validation error message" do
post :create, {:app_city => { "name" => "" }, :v => "HEAD", :access_token => token.token}, valid_session
response_body = JSON.parse(response.body, symbolize_names: true)
expect(response_body[:name]).to include "can't be blank"
end
it "returns a 422 status" do
post :create, {:app_city => { "name" => "" }, :v => "HEAD", :access_token => token.token}, valid_session
response.status.should eq(422)
end
end
end
【问题讨论】:
-
你不是也需要申请创建的token吗?以某种方式在请求中提供它?您能否提供更完整的测试,包括设置、实际测试和有效负载?
-
@EmilKampp 我已经编辑了问题以包含实际测试
标签: ruby-on-rails ruby-on-rails-4 rspec devise doorkeeper