I am trying to create a test for a model which has a photo as a mandatory association. This is my model:
class Car < ApplicationRecord
has_one_attached :photo
validates :name, uniqueness: true
validates :name, presence: true
validates :photo, presence: true
end
and this is my test:
require 'rails_helper'
RSpec.describe 'Car', type: :model do
let(:valid_attributes) do
{
name: 'Audi'
}
end
it 'name is unique' do
Car.create!(name: 'Audi')
car = Car.new(name: 'Audi')
expect(car).not_to be_valid
end
end
The result of the test is:
Failures:
1) Car name is unique
Failure/Error: Car.create!(name: 'Audi')
ActiveRecord::RecordInvalid:
Validation failed: Photo can't be blank
# ./spec/models/car_model_spec.rb:23:in `block (2 levels) in <main>'
What I can't do is attach a photo for testing. Do you have any tips?
As you have guessed, to pass the validation, you have to add a picture to your test :)
require 'rails_helper'
RSpec.describe 'Car', type: :model do
let(:valid_attributes) do
{
name: 'Audi'
}
end
let(:photo) do
Rack::Test::UploadedFile.new(
Rails.root.join('path/to/image.png'), 'image/png'
)
end
it 'name is unique' do
Car.create!(name: 'Audi', photo: photo)
car = Car.new(name: 'Audi', photo: photo)
expect(car).not_to be_valid
end
end