How to properly do model testing with ActiveStorage in rails?

前端 未结 5 651
星月不相逢
星月不相逢 2021-01-01 09:17

I have just switched to using ActiveStorage on rails 5.1.4 and I am new to TDD and struggling to figure out how to test a model that has_one_attached :avatar

5条回答
  •  一个人的身影
    2021-01-01 10:06

    Here is how I solved it

    # model
    class Report < ApplicationRecord
      has_one_attached :file
    end
    
    # factory
    FactoryBot.define do
      factory :report, class: Report do 
        any_extra_field { 'its value' }
      end
    end
    
    # spec
    require '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
      end
    end
    

    I hope it help you

提交回复
热议问题