March 2, 2016
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
If this blog was helpful, check out our full blog archive.