fake-file
fake-file is a Ruby gem for generating temporary fake files for tests.
It helps when you need to attach a file to a model (ActiveStorage, Shrine, CarrierWave, etc.) without storing fixture files in spec/files.
Currently supported formats:
pdfdocxxlsx
Installation
Add to your app's Gemfile:
gem "fake-file"Then run:
bundle installOr install manually:
gem install fake-fileQuick Start
require "fake-file"
pdf_file = FakeFile.pdf
docx_file = FakeFile.docx
xlsx_file = FakeFile.xlsxEach method returns a Tempfile object ready to use in tests.
API
Facade methods
FakeFile.pdf(options = {})
FakeFile.docx(options = {})
FakeFile.xlsx(options = {})Generic generator
FakeFile.generate(:pdf)
FakeFile.generate(:docx)
FakeFile.generate(:xlsx)Rack::Test uploaded file helper
FakeFile.upload(:pdf)
FakeFile.upload(:docx)
FakeFile.upload(:xlsx)Returns Rack::Test::UploadedFile, so you can use it directly in request specs.
Usage in tests
ActiveStorage example
it "attaches generated pdf" do
file = FakeFile.pdf
record.file.attach(
io: file,
filename: "sample.pdf",
content_type: "application/pdf"
)
expect(record.file).to be_attached
endVerify MIME type
require "marcel"
expect(Marcel::MimeType.for(FakeFile.docx))
.to eq("application/vnd.openxmlformats-officedocument.wordprocessingml.document")Request spec with Rack::Test
post "/imports", params: { file: FakeFile.upload(:xlsx) }Adding a new format
- Create a new generator class in
lib/fake-file/generators/. - Inherit from
BaseGeneratorand implement#generate. - Register it in
lib/fake-file.rb:
Registry.register(:txt, Generators::TxtGenerator.new)After that, it becomes available via:
FakeFile.generate(:txt)Development
Install dependencies:
bundle installRun specs:
ruby -S bundle exec rspecOpen console:
bin/consoleContributing
Issues and pull requests are welcome:
Please follow CODE_OF_CONDUCT.md.
License
The gem is distributed under the MIT license. See LICENSE.txt.