# Easily generate test files of any size

> Anyone who has implemented file uploads, with file size validations, knows how annoying it is to test. As Chris shows, creating files of a correct size can be fast and easy.

- URL: https://velocitylabs.io/blog/2018/06/04/easily-generate-test-files-of-any-size/
- Published: June 4, 2018
- Author: Chris Irish

### The problem

Say you have a file upload validation in one of your Rails models. This validation limits the size of an uploaded file to 10 Mb.

You now want to test the upload validation size limit works correctly (manually or automated).

So you start searching your Documents folder, hoping to find a couple files that will work.

You want one file that’s just below 10 Mb limit and another that is just above 10 Mb. This can be cumbersome and you just may not have local files that fit the bill.

_What can we do instead?_

### The solution

How about dynamically generate a file of the exact size we need?

We can accomplish this using the **dd unix command**. So let’s try creating a file of exactly 10 Mb in size.

 $ dd if=/dev/random of=test.txt bs=1024 count=10240
 10240+0 records in
 10240+0 records outt
 10485760 bytes transferred in 0.859163 secs (12204622 bytes/sec)

What were saying here is, read data from /dev/random, into a new file called ‘test.txt’, in 1024-byte size blocks (1 KB), and give me 10,240 of them (10 Mbs is 10,240 KB).

We can verify this file is the correct size with

 $ ls -lah test.txt
 -rw-r--r--+ 1 supairish staff 10M Jun 4 17:42 test.txt

Excellent!

So just rerun this command with a smaller or larger count number to get the exact file sizes you need and you’re good to go.

_Just remember: **1 Mb is 1,024 KB** _

You could also wrap this command in a spec helper to use in MiniSpec or Rspec and generate files of random size ranges during your runs.

Just remember to cleanup/delete in your teardowns so you don’t accidentally eat up disk space.
