更新:ユニットテスト(現在は/ libにある1つのモジュールのみ)がrake test
で実行されると、Rails環境がロードされていないためです。レーキタスク自体を変更するのではなく、コマンドラインから環境を含めることは可能ですか?これについてもっと良い方法がありますか(Rails.loggerを導入するために依存性注入を使用するのは簡単ではありません。Rails.loggerはテスト環境では何故ですか?
私はRails.logger.error
にあるため、次の呼び出しの私のテスト環境でNoMethodError
を見ている:
# /lib/square.rb
module Square
def self.get_total_sales_for_location(location_id, timeout: 5)
begin
url = "https://connect.squareup.com/v2/locations/#{location_id}/transactions"
headers = {Authorization: "Bearer #{ENV['SQUARE_PERSONAL_ACCESS_TOKEN']}"}
response = RestClient::Request.execute headers: headers,
method: :get,
timeout: timeout,
url: url
if response.code == 200
JSON.parse response.body
else
fail
end
rescue => error
Rails.logger.error "Square::get_total_sales_for_location - #{error.message}"
raise
end
end
end
このすべては、しかし、で私のテストの結果を実行し、コンソールから正常に動作します:NoMethodError: undefined method 'error' for nil:NilClass
をマイ一時的なの回避策は、例外を防ぐために:try
を使用することですが、それは非常にクルージングです。
あなたのコードサンプルでは動作しないRails.logger.logを使用しています –
Rails.logger.infoまたはRails.logger.debug –
それを指摘してくれてありがとう。私のコードは実際には「エラー」を使用していますが、それは翻訳で失われました。 – pdoherty926