LoginSignup
10
7

More than 5 years have passed since last update.

ActiveStorageを使用したモデルに関連するRequest SpecでActiveSupport::MessageVerifier::InvalidSignatureが発生する問題の解決策

Last updated at Posted at 2018-08-09

やろうとしたこと

ActiveStorageを使用したモデルでnameカラムの変更テストをした際、ActiveSupport::MessageVerifier::InvalidSignatureが原因で失敗することがありました。

hoge.rb
class Hoge < ApplicationRecord
  .
  .
  .
  has_one_attached :attached
  .
  .
  .
end
hoge_factory.rb
FactoryBot.define do
  factory :hoge do
    name { Faker::Name.name }
    .
    .
    .
    attached { fixture_file_upload(Rails.root.join('spec', 'fixtures', 'files', 'test.jpg'), 'image/jpg') }
    .
    .
    .
    trait :edit do
      name "HOGE"
    end
  end
end
hoges_spec.rb
require 'rails_helper'

RSpec.describe "Hoges", type: :request do
  .
  .
  .
  describe 'PUT #update' do
    let!(:hoge) { create(:hoge) }

    context 'when sign_in admin user' do
      before do
        sign_in @admin_user
      end

      it 'can update name' do
        # テストが失敗したので、例外の内容を出力してみると、「ActiveSupport::MessageVerifier::InvalidSignature」だった
        expect do
          put bad_report_url bad_report, params: { bad_report: attributes_for(:bad_report, :edit) }
        end.to change { BadReport.find(hoge.id).name }.from(hoge.name).to("HOGE")
      end
    end
  end
  .
  .
  .
end

解決策

after(:build)の中でfixture_file_uploadするようにします。

-    attached { fixture_file_upload Rails.root.join('spec', 'fixtures', 'files', 'test.jpg'), 'image/jpg' }
+    
+    after(:build) do |hoge|
+      hoge.attached = fixture_file_upload(Rails.root.join('spec', 'fixtures', 'files', 'test.jpg'), 'image/jpg')
+    end

参考: https://stackoverflow.com/questions/47583883/how-to-properly-do-model-testing-with-activestorage-in-rails

10
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
7