The Rails app that I'm currently developing has the ability to allow users to set a profile image. This time I wrote a test to see if the function is working properly, so please refer to it if you like!
【environment】
We are testing with system specifications.
spec/system/upload_avatar_spec.rb
require 'rails_helper'
RSpec.describe'UploadImage', type: :system do
let(:user) { FactoryBot.create(:user) }
let(:item) { FactoryBot.create(:item, user_id: user.id) }
#Upload and save images
def upload_user_avatar(user)
valid_login(user)
visit edit_user_path(user)
attach_file 'user_avatar', "#{Rails.root}/spec/fixtures/images/test.jpg "
click_on 'save'
end
it 'user successfully upload image user#show' do
upload_user_avatar(user)
expect(page).to have_selector("img[src$='test.jpg']")
end
it 'user successfully upload image on item#show' do
upload_user_avatar(user)
visit item_path(item)
expect(page).to have_selector("img[src$='test.jpg']")
end
end
The valid_login method is defined in `` `spec / support / login_support.rb```. The methods defined in this folder can be called during testing. I'm writing this code because my app only allows access to edit_user_path when I'm logged in. If you do not write it, it will fail. (I have to fail)
spec/support/login_support.rb
module LoginSupport
def valid_login(user)
visit root_path
click_link 'Login'
fill_in 'session[email]', with: user.email
fill_in 'session[password]', with: user.password
click_button 'Login'
end
end
I will explain in order. First, generate test data for user and item with ** FactoryBot **. (It is necessary to define the test data in ``` spec / factries /` `` in advance. I will omit it here.)
The act of uploading an image is common to all blocks, so it is defined collectively as the upload_user_avatar method.
In this method, you log in, go to the user's edit page, and use the attach_file method to upload and save the test image data.
You need to prepare test images in `/ spec / fixtures / images /`
in advance.
Also, I specified the id of the input tag generated by f.file_field as the argument of the attach_file method and it worked! (See image. You can check the generated HTML from the developer tools.)
We are doing two tests this time.
First, when the image is uploaded, it checks if the image data is in the redirect destination specified by the controller. I am using have_selector to check if the image data of test.jpg is included in the src attribute of the img tag.
The second one is almost the same. Since the same image is also used on the post detail page, I go to the post detail page and use have_selector to check if the image data of test.jpg is included in the src attribute of the img tag.
I output what I learned every day! !! If you have any impressions or suggestions, I would appreciate it if you could comment! !!
Recommended Posts