This blog is part of our Rails 5 series.
While writing tests sometimes we need to read files to compare the output. For example a test might want to compare the API response with pre determined data stored in a file.
Here is an example.
# In test helper
def file_data(name)
File.read(Rails.root.to_s + "/tests/support/files/#{name}")
end
# In test
class PostsControllerTest < ActionDispatch::IntegrationTest
setup do
@post = posts(:one)
end
test "should get index" do
get posts_url, format: :json
assert_equal file_data('posts.json'), response.body
end
end
In Rails 5, we can now organize such test files as fixtures.
Newly generated Rails 5 applications, will have directory test/fixtures/files
to store such test files.
These test files can be accessed using file_fixture helper method in tests.
require 'test_helper'
class PostsControllerTest < ActionDispatch::IntegrationTest
setup do
@post = posts(:one)
end
test "should get index" do
get posts_url, format: :json
assert_equal response.body, file_fixture('posts.json').read
end
end
The file_fixture method returns Pathname object, so it's easy to extract
file specific information.
file_fixture('posts.json').read
file_fixture('song.mp3').size

Written byErshad Kunnakkadan
Related blogs
- 01Rails 5 Active Record attributes APIDecember 11, 2018 · Abhay Nikam
- 02Rails 5 Create module and class level variablesSeptember 5, 2016 · Abhishek Jain
- 03Rails 5 silences assets logs in dev mode by defaultSeptember 2, 2016 · Midhun Krishna
- 04Rails 5 disables autoloading while app in productionAugust 29, 2016 · Shailesh Kalamkar