我目前正在为通过Boxr gem与Box API交互的Proxy类编写测试。我正在从.env.test.local
文件中加载环境密钥。该文件中的密钥是垃圾,因此从理论上讲应该可以,但是出现以下错误:
OpenSSL::PKey::RSAError:
Neither PUB key nor PRIV key: not enough data
我正在使用Webmock进行测试。我使用以下内容编辑spec_helper.rb
文件。
# Configuration for Boxr mocking libraries for testin
config.before(:suite) do
Boxr::BOX_CLIENT = HTTPClient.new
end
config.before(:each) do
stub_const('ENV', {'BOX_USER_ID' => '123',
'BOX_CLIENT_SECRET' => "345",
'BOX_DEVELOPER_TOKEN' => "123",
'BOX_CLIENT_ID' => "1234",
'JWT_PRIVATE_KEY' => 'hello',
'JWT_PRIVATE_KEY_PASSWORD' => '1234545677',
'JWT_PUBLIC_KEY_ID' => "12345467"})
stub_request(:post, "https://api.box.com/oauth2/token").
with(:body => {"assertion"=>ENV["ASSERTION"], "client_id"=>ENV["BOX_USER_ID"], "client_secret"=>ENV["BOX_CLIENT_SECRET"], "grant_type"=>"urn:ietf:params:oauth:grant-type:jwt-bearer"},
:headers => {'Accept'=>'*/*', 'Content-Type'=>'application/x-www-form-urlencoded', 'Date'=>'Time.now', 'User-Agent'=>'HTTPClient/1.0 (2.8.3, ruby 2.5.3 (2018-10-18))'}).
to_return(:status => 200, :body => "", :headers => {})
end
我在环境密钥中添加了垃圾数据,但现在确定这是否是加载环境密钥进行测试的正确方法。
这是我一直在进行的测试。
require './src/clients/box_api'
require 'dotenv'
require 'pry'
Dotenv.load('.env.test.local')
RSpec.describe BoxApi do
describe '#client' do
context 'success' do
it 'Create Boxr::Client object' do
# setup
box_api = BoxApi.new
# exercise
result = box_api.client
# verify
expect(result.class).to eq Boxr::Client
end
end
context 'fail' do
it 'Fails to create Boxr::Client object' do
expect { Boxr::Client.new(nil) }.to raise_error(Boxr::BoxrError)
end
end
end
describe '#folder' do
context 'success' do
it 'Retrieves a folder from Box' do
stub_request(:get, "http://api.box.com/folders/123").to_return(body: {id: "123"}.to_json )
box_api = BoxApi.new
expect(box_api.folder("123")).to eq({id: "123"})
end
end
context 'fail' do
it 'Raise error for folder not found' do
stub_request(:get, "http://api.box.com/folders/123").to_return(body: {id: "123"}.to_json )
box_api = BoxApi.new
expect(box_api.folder("N")).to raise_error(Boxr::BoxrError)
end
end
end
end
从client
实例调用BoxApi
时似乎会引发错误。
require 'boxr'
class BoxApi
attr_reader :user_id, :private_key, :private_key_password, :public_key_id,
:client_id, :client_secret, :box_folder_id, :box_domain
def initialize
@user_id = ENV.fetch('BOX_USER_ID')
@private_key = ENV.fetch('JWT_PRIVATE_KEY')
@private_key_password = ENV.fetch('JWT_PRIVATE_KEY_PASSWORD')
@public_key_id = ENV.fetch('JWT_PUBLIC_KEY_ID')
@client_id = ENV.fetch('BOX_CLIENT_ID')
@client_secret = ENV.fetch('BOX_CLIENT_SECRET')
end
def client
@client ||= Boxr::Client.new(token.access_token)
end
def token
Boxr.get_user_token(@user_id,
private_key: @private_key,
private_key_password: @private_key_password,
public_key_id: @public_key_id,
client_id: @client_id,
client_secret: @client_secret)
end
def prepare_folder(folder_id)
client.folder_from_id(folder_id)
end
def folder(box_folder_id)
prepare_folder(box_folder_id)
end