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.
1 2# In test helper 3def file_data(name) 4 File.read(Rails.root.to_s + "/tests/support/files/#{name}") 5end 6 7# In test 8class PostsControllerTest < ActionDispatch::IntegrationTest 9 setup do 10 @post = posts(:one) 11 end 12 13 test "should get index" do 14 get posts_url, format: :json 15 16 assert_equal file_data('posts.json'), response.body 17 end 18end 19
File Fixtures in Rails 5
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.
1require 'test_helper' 2 3class PostsControllerTest < ActionDispatch::IntegrationTest 4 setup do 5 @post = posts(:one) 6 end 7 8 test "should get index" do 9 get posts_url, format: :json 10 11 assert_equal response.body, file_fixture('posts.json').read 12 end 13end
The file_fixture method returns Pathname object, so it's easy to extract file specific information.
1file_fixture('posts.json').read 2file_fixture('song.mp3').size