RSPEC 로이 코드를 테스트하는 방법은 무엇입니까?
-
10-12-2019 - |
문제
나는 다음과 같은 간단한 클래스와 htttHarty 메소드를 가지고있다 :
class Token
require 'httparty'
include HTTParty
base_uri 'https://<some url>'
headers 'auth_user' => 'user'
headers 'auth_pass' => 'password'
headers 'auth_appkey' => 'app_key'
def self.getToken
response = get('/auth/token')
@token = response['auth']['token']
end
end
.
RAILS 콘솔에서 메서드를 호출하고 토큰을 다시 성공적으로 가져올 수 있기 때문에 작동합니다 작동합니다.
위의 코드를 RSPEC에서 어떻게 테스트 할 수 있습니까?
내 초기 찌르기가 작동하지 않습니다 :
.
describe Token do
before do
HTTParty.base_uri 'https://<some url>'
HTTParty.headers 'auth_user' => 'user'
HTTParty.headers 'auth_pass' => 'password'
HTTParty.headers 'auth_appkey' => 'app_key'
end
it "gets a token" do
HTTParty.get('auth/authenticate')
response['auth']['token'].should_not be_nil
end
end
그것은 말합니다 : NoMethodError: undefined method 'base_uri' for HTTParty:Module
...
감사합니다!
해결책
모듈을 테스트하고 있기 때문에 다음과 같이 시도 할 수 있습니다.
describe Token do
before do
@a_class = Class.new do
include HTTParty
base_uri 'https://<some url>'
headers 'auth_user' => 'user'
headers 'auth_pass' => 'password'
headers 'auth_appkey' => 'app_key'
end
end
it "gets a token" do
response = @a_class.get('auth/authenticate')
response['auth']['token'].should_not be_nil
end
end
.
이렇게하면 익명 클래스가 생성되고 HTTPparty
의 클래스 메소드로 확장됩니다.그러나 응답이 당신이 가지고있는 것처럼 반환 할 것으로 확신하지 못합니다.