We need to use File.open(Rails.root.join("<image_path>"))
.
File.open(Rails.root.join("test/fixtures/files/sample.jpeg"))
Example:
# group_test.rb
test "is valid" do
assert fake_group.valid?
end
def fake_group(params = {})
@fake_group ||= Group.new(
owner: params[:owner] || users(:phil),
name: params[:name] || "Test group",
description: params[:description] || "Test group description.",
image: params[:image] || valid_image
)
end
def valid_image
File.open(Rails.root.join("test/fixtures/files/sample.jpeg"))
end
We need to use fixture_file_upload("<image_path>", "image/<extension>"
.
fixture_file_upload("test/fixtures/files/sample.jpeg", "image/jpeg")
Example:
# groups_controller_test.rb
test "should create group" do
user = users(:phil)
log_in_as(user)
assert_difference("Group.count") do
post groups_url, params: { group: {
name: "Test group",
description: "Test group description.",
image: upload_valid_image
} }
end
assert_redirected_to group_url(Group.last)
end
def upload_valid_image
fixture_file_upload("test/fixtures/files/sample.jpeg", "image/jpeg")
end
We need to use attach_file("<image_id>", "<image_path>")
.
attach_file "group_image", "test/fixtures/files/sample.jpeg"
Example:
# groups_creation_test.rb
test "user creates a group" do
user = users(:phil)
log_in_as(user)
visit root_path
within ".navbar" do
click_on user.name
end
within ".dropdown-menu" do
click_on "Create group"
end
fill_in "Name", with: "Test group"
fill_in "Description", with: "Test group description."
attach_valid_image
within "form" do
click_on "Create group"
end
assert page.has_content? "Yay! You created a group!"
end
def attach_valid_image
attach_file "group_image", "test/fixtures/files/sample.jpeg"
end