require "ar_helper" require "study_engine/study_id/sync" require "study_engine/study_id/bank" require "webmock/rspec" module StudyEngine describe StudyID::Sync do let(:csv) { <<-CSV } study_id,stream_api_complete FIX-AAA-1000,0 FIX-AAA-1001,0 FIX-BBB-1001,0 OUT-AAA-1000,0 CSV before do StudyEngine.redcap_token = "omgwtfbbq" stub_request(:post, "https://metrcdata.org/redcap/api/"). with(body: { "content"=>"record", "format"=>"csv", "token"=>"omgwtfbbq" }). to_return(body: csv) end describe ".call" do it "adds new study ids" do expect { described_class.call }.to change { StudyID::Bank.count }.by(4) end it "deletes old nonexistent study ids" do attributes = { study_id_study: "OMG", study_id_site: "WTF", study_id_id: "1234" } StudyID::Bank.create(attributes.merge(updated_at: 1.hour.ago)) expect { described_class.call }.to change { StudyID::Bank.where(attributes).count }.by(-1) end it "raises an error when redcap token is not configured" do StudyEngine.redcap_token = "" expect { described_class.call }.to raise_exception("Cannot sync with REDCap without setting StudyEngine.redcap_token") end it "retries request on network timeout" do call_count = 0 allow(Faraday).to receive(:new).and_wrap_original do |original, *args| call_count += 1 if call_count == 1 raise Faraday::TimeoutError else original.call(*args) end end expect { described_class.call }.to change { StudyID::Bank.count }.by(4) expect(call_count).to eq(2) end end end end