패러데이로 루비를 스터빙했는데 제대로 작동하지 못함
문제
제목이 아쉽네요. 지금은 더 나은 것을 생각해내기에는 너무 답답합니다.
수업이 있어요, Judge
, 메소드가 있습니다. #stats
.이것 통계 메소드는 API에 GET 요청을 보내고 응답으로 일부 데이터를 가져옵니다.실제 요청을 수행하지 않도록 이를 테스트하고 stats 메서드를 스텁하려고 합니다.내 테스트는 다음과 같습니다.
describe Judge do
describe '.stats' do
context 'when success' do
subject { Judge.stats }
it 'returns stats' do
allow(Faraday).to receive(:get).and_return('some data')
expect(subject.status).to eq 200
expect(subject).to be_success
end
end
end
end
제가 테스트하고 있는 수업은 다음과 같습니다.
class Judge
def self.stats
Faraday.get "some-domain-dot-com/stats"
end
end
현재 나에게 오류가 발생합니다. Faraday does not implement: get
그러면 이것을 패러데이로 어떻게 스텁합니까?나는 다음과 같은 방법을 보았습니다.
stubs = Faraday::Adapter::Test::Stubs.new do |stub|
stub.get('http://stats-api.com') { [200, {}, 'Lorem ipsum'] }
end
하지만 올바른 방법으로 적용할 수는 없는 것 같습니다.내가 여기서 무엇을 놓치고 있는 걸까요?
해결책
FARADAY.NEW는 FARADAY가 아닌 FARADAY :: Connection의 인스턴스를 반환합니다.따라서
를 사용해 볼 수 있습니다allow_any_instance_of(Faraday::Connection).to receive(:get).and_return("some data")
.
Faraday :: Connection.Get은 문자열 대신 본문 및 상태 코드를 포함하는 응답 개체를 반환해야합니다.당신은 다음과 같이 시도 할 수 있습니다 :
allow_any_instance_of(Faraday::Connection).to receive(:get).and_return(
double("response", status: 200, body: "some data")
)
.
여기에 FARADAY에서 돌아 오는 클래스를 보여주는 레일 콘솔이 있습니다 .NEW
$ rails c
Loading development environment (Rails 4.1.5)
2.1.2 :001 > fara = Faraday.new
=> #<Faraday::Connection:0x0000010abcdd28 @parallel_manager=nil, @headers={"User-Agent"=>"Faraday v0.9.1"}, @params={}, @options=#<Faraday::RequestOptions (empty)>, @ssl=#<Faraday::SSLOptions (empty)>, @default_parallel_manager=nil, @builder=#<Faraday::RackBuilder:0x0000010abcd990 @handlers=[Faraday::Request::UrlEncoded, Faraday::Adapter::NetHttp]>, @url_prefix=#<URI::HTTP:0x0000010abcd378 URL:http:/>, @proxy=nil>
2.1.2 :002 > fara.class
=> Faraday::Connection
. 다른 팁
FARADAY 클래스는 get
메소드가 없으며 인스턴스 만 수행합니다.클래스 메소드 에서이 작업을 사용하고 있으므로 다음과 같은 것입니다.
class Judge
def self.stats
connection.get "some-domain-dot-com/stats"
end
def self.connection=(val)
@connection = val
end
def self.connection
@connection ||= Faraday.new(some stuff to build up connection)
end
end
.
그런 다음 테스트에서 당신은 그냥 두 배로 설정할 수 있습니다 :
let(:connection) { double :connection, get: nil }
before do
allow(connection).to receive(:get).with("some-domain-dot-com/stats").and_return('some data')
Judge.connection = connection
end
. 나는 같은 문제에 부딪쳤다. Faraday::Adapter::Test::Stubs
오류가 발생했습니다. Faraday does not implement: get
.설정을 하셔야 할 것 같습니다 stubs
다음과 같이 패러데이 어댑터에:
stubs = Faraday::Adapter::Test::Stubs.new do |stub|
stub.get("some-domain-dot-com/stats") { |env| [200, {}, 'egg'] }
end
test = Faraday.new do |builder|
builder.adapter :test, stubs
end
allow(Faraday).to receive(:new).and_return(test)
expect(Judge.stats.body).to eq "egg"
expect(Judge.stats.status).to eq 200