web-dev-qa-db-ja.com

レールでActiveStorageを使用してモデルテストを適切に行う方法

Rails 5.1.4でActiveStorageを使用するように切り替えました。TDDを初めて使用し、has_one_attached :avatar

require 'Rails_helper'

RSpec.describe User, :type => :model do

  let (:valid_user) { FactoryBot.build(:user) }
  describe "Upload avatar" do
    context "with a valid image" do      
      it "saves the image" do
        valid_user.save!        
        saved_file = valid_user.avatar.attach(io: File.open("/home/ubuntu/workspace/spec/fixtures/files/avatar.jpg"), filename: "face.jpg", content_type: "image/jpg")
        expect(saved_file).to be_an_instance_of(ActiveStorage::Attachment::One)
      end
    end
  end 

end

しかし、次のエラーが表示されます。

Failures:

  1) User Upload avatar with a valid image saves the image
     Failure/Error:
       saved_file = valid_user.avatar.attach(io: File.open("/home/ubuntu/workspace/spec/fixtures/files/avatar.jpg"), filename: "face.jpg", 
                                             content_type: "image/jpg")


 NoMethodError:
   undefined method `upload' for nil:NilClass
   Did you mean?  load
 # /usr/local/rvm/gems/Ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/blob.rb:48:in `upload'
 # /usr/local/rvm/gems/Ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/blob.rb:21:in `block in build_after_upload'
 # /usr/local/rvm/gems/Ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/blob.rb:16:in `tap'
 # /usr/local/rvm/gems/Ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/blob.rb:16:in `build_after_upload'
 # /usr/local/rvm/gems/Ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/blob.rb:26:in `create_after_upload!'
 # /usr/local/rvm/gems/Ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/attached.rb:25:in `create_blob_from'
 # /usr/local/rvm/gems/Ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/attached/one.rb:9:in `attach'
 # ./spec/models/user_spec.rb:47:in `block (4 levels) in <top (required)>'

ヒントはありますか?

24
Donato Azevedo

を使用して解決しました

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
  end
end

describe '#image' do
  subject { create(:culture).image }

  it { is_expected.to be_an_instance_of(ActiveStorage::Attached::One) }
end
16
vgsantoniazzi

問題が解決しました。 ActiveStorage :: Blob :: uploadメソッドにエラーをトレースした後、次のように言いました:Uploads the io to the service on the key for this blob.テスト環境にactive_storage.serviceを設定していないことに気付きました。簡単に言えば、追加するだけです:

config.active_storage.service = :test

Config/environments/test.rbファイルへ

15
Donato Azevedo

Config/environments/test.rb内

_config.active_storage.service = :test_

あなたのスペックで

it {expect(valid_user.avatar).to be_attached}

0
rexmadden