Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialClair Griffiths
10,158 PointsTesting file attachment with Capybara
Hi all
I'm struggling to get a test to pass in Capybara. When I'm uploading a post I have a validation that makes sure that I've attached a file but I can't seem to replicate this behaviour in a test.
My form looks like this:
<%= form_for @post do |form| %>
<%= form.label :title %>
<%= form.text_field :title %>
<%= form.label :category %>
<%= form.text_field :category %>
<%= form.label :image %>
<%= form.file_field :image %>
<%= form.submit %>
<% end %>
My test looks like this:
describe "Create posts"
it "Saves a post on success" do
visit '/'
click_link "Add new post"
fill_in "Title", with: "My new post"
fill_in "Category", with: "Questions"
page.attach_file("image", Rails.root + 'app/assets/images/imagename.jpg')
click_button "Create Post"
expect(page).to have_content("My new post")
end
end
and the error message I'm getting is:
1) Login Saves a post on success
Failure/Error: page.attach_file("image", Rails.root + 'app/assets/images/imagename.jpg')
Capybara::ElementNotFound:
Unable to find file field "image"
I don't really understand why it is saying it can't find a file field called 'image' when that is exactly what I've called it in the form!
Any help would be gratefully recieved. Thanks in advance.
2 Answers
Seth Reece
32,867 PointsYou probably need to specify a class (or id) name of image in your form. If nested under a post, rails probably gave it an id of post_image, and a name of post[image] or something to that effect.
Corey Gibson
Courses Plus Student 4,044 PointsMake you "image" in testing "Image"
Clair Griffiths
10,158 PointsClair Griffiths
10,158 PointsThanks Seth!
I'm pretty sure it's working (although my test is failing for other reasons now so I can't be fully sure)
In the end, I inspected the element and found that, exactly as you'd said, the field had been given an id of "post_image" and a name of "post[image]".
I substituted this in the code as per below and it now seems to work
page.attach_file("post_image", Rails.root + 'app/assets/images/imagename.jpg')
Thanks again!