Table of Content
Writing the photo upload component
How about uploading files?
We can create a feature to test it.
1Feature: Photo Upload 2 Scenario: Uploading link 3 Given I am on homepage 4 When I click "Upload photo" link 5 Then I should be on the photo upload page 6 7 Scenario: Uploading photo 8 Given I am on photo upload page 9 When I upload a valid photo with title "Test" 10 Then I should see "Success" 11 And I should see "Test" 12 13 Scenario: Uploading invalid photo 14 Given I am on photo upload page 15 When I upload an invalid photo with title "Test" 16 Then I should see "Error"
Again, lot’s of errors/pendings and it is absolutely normal.
The first error is the missing “Upload photo” link. Easy one, Let’s create a link.
1<%= link_to 'Upload photo', '#' %>
Yes, link to '#'
now because we just want minimal code to make the test works.
Then we add the pending step one by one. The next one is the I should be on the photo upload page
.
Run the rake cucumber
again and we get expected: "/photos/new" got: "/"'
error. That’s good, it indicates that we can finally create the photo model and controllers. Don’t write unnecessary code until the last minute.
In order to make the case passes, we need the photo resource and a photo upload page.
First, it is about the routes.
Next, the model.
Then make the photo.rb file match the following.
And the controller with new
action.
$ rails generate controller photos new
The controller file.
And the related view.
Nice, now we should now passes all existing cases with some pendings steps.
The next pending is I am on photo upload page
which should be just a visit method.
Then it is the I upload a valid photo
step, which requires us to prepare a dummy PNG file and place it in the features/upload_files
folder. (You can use any folder indeed)
But how to write the step for file uploading? Here it is.
Now we got the The action 'create' could not be found for PhotosController
error. Well, we haven’t handle the form POST yet.
And here we define the create
method in photos_controller file.
This time cucumber generates another great failing: The action 'show' could not be found for PhotosController
. It is like a virtual mentor telling us what to do next – the show method.
In the photos controller.
The view views/photos/show.html.erb
.
Great! The photo upload works and passes. Next one we will try to upload a non-image file.
The cucumber shows an error that the txt file is successfully uploaded. That’s because we haven’t added any file format validation to the model yet. We can do that by adding the following code to the Photo model class, photo.rb
file.
1validates_attachment :image, presence: true, content_type: ["image/jpg", "image/png"]
Wonderful, all tests passed now.
What’s next? We’re going to take a look at “What’s Next”.