require 'rails_helper'

module Attachments
  describe HostedImage do
    describe "#get_s3_url" do
      it "fails if object already exists" do
        allow(Aws::S3::Client).to receive(:new).and_return(Aws::S3::Client.new(stub_responses: true))
        expect_any_instance_of(Aws::S3::Object).to receive(:exists?).and_return(true)

        hi = HostedImage.new(:filename => "test")
        success = hi.save
        expect(success).to be false
        expect(hi.errors.full_messages).to eq(["failed to get presigned s3 url. err: attachment test already exists."])
      end

      it "fails to get pre signed url" do
        allow(Aws::S3::Client).to receive(:new).and_return(Aws::S3::Client.new(stub_responses: true))
        expect_any_instance_of(Aws::S3::Object).to receive(:exists?).and_return(false)
        expect_any_instance_of(Aws::S3::Presigner).to receive(:presigned_url).and_raise(ArgumentError.new("failed"))

        hi = HostedImage.new(:filename => "test")
        success = hi.save
        expect(success).to be false
        expect(hi.errors.full_messages).to eq(["failed to get presigned s3 url. err: failed"])
      end

      it "returns presigned url" do
        url = "test_url"
        allow(Aws::S3::Client).to receive(:new).and_return(Aws::S3::Client.new(stub_responses: true))
        expect_any_instance_of(Aws::S3::Object).to receive(:exists?).and_return(false)
        expect_any_instance_of(Aws::S3::Presigner).to receive(:presigned_url).and_return(url)

        hi = HostedImage.new(:filename => "test")
        success = hi.save
        expect(success).to be true
        expect(hi.s3_url).to equal(url)
      end
    end
  end
end
