Skip to content

Instantly share code, notes, and snippets.

@nickcharlton
Last active May 24, 2022 09:41
Show Gist options
  • Save nickcharlton/1e226bf44401c014a958b57ae35968f6 to your computer and use it in GitHub Desktop.
Save nickcharlton/1e226bf44401c014a958b57ae35968f6 to your computer and use it in GitHub Desktop.
RSpec: Testing ActiveStorage

RSpec: Testing ActiveStorage

Testing file uploads in ActiveStorage is a little awkward. Fortunately, fixtures comes to the rescue and we can provide a file to be passed through to the parameters. This works across model and system/feature specs.

In your factory, you might define it like:

factory :document do
    name { "Example File" }

    file do
      Rack::Test::UploadedFile.new(
        Rails.root.join("spec/fixtures/files/example.pdf"),
      )
    end
  end

At creation point, you might override this:

create(:document, name: "A new file",
  file: Rack::Test::UploadedFile.new(
    file_fixture("example.png"),
  )
)

And then in a spec:

it "uploads a file" do
  form = UploadDocumentForm.new(name: "Example File", file: test_file)

  expect { form.save }.to change(UploadDocumentForm, :count).by(1)

  def test_file
    Rack::Test::UploadedFile.new(file_fixture("example.pdf"))
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment