How to properly do model testing with ActiveStorage in rails?
I solved using
FactoryBot.define do factory :culture do name 'Soy' after(:build) do |culture| culture.image.attach(io: File.open(Rails.root.join('spec', 'factories', 'images', 'soy.jpeg')), filename: 'soy.jpeg', content_type: 'image/jpeg') end endend
After
describe '#image' do subject { create(:culture).image } it { is_expected.to be_an_instance_of(ActiveStorage::Attached::One) }end
Problem solved. After tracing the error to the ActiveStorage::Blob::upload method, where it said: Uploads the io to the service on the key for this blob.
I realized I had not set the active_storage.service for the Test environment. Simply put, just add:
config.active_storage.service = :test
To config/environments/test.rb file
Here is how I solved it
# modelclass Report < ApplicationRecord has_one_attached :fileend
# factoryFactoryBot.define do factory :report, class: Report do any_extra_field { 'its value' } endend
# specrequire 'rails_helper'RSpec.describe Report, type: :model do context "with a valid file" do before(:each) do @report = create(:report) end it "is attached" do @report.file.attach( io: File.open(Rails.root.join('spec', 'fixtures', 'file_name.xlsx')), filename: 'filename.xlsx', content_type: 'application/xlsx' ) expect(@report.file).to be_attached end endend
I hope it help you