Search code examples
ruby-on-railsminitestrails-activestorage

Testing in an ActiveStorage context


In following the rails guides regarding testing, the following was effected for two classes that have attachments (using a french naming variant, which is close enough to the reserved 'file')

class Picture < ApplicationRecord
  has_one_attached :fichier do |attachable|
    attachable.variant :thumb, resize_to_limit: [100, 100]
    attachable.variant :small, resize_to_limit: [250, 250]
  end
[...]
class Document < ApplicationRecord
  has_one_attached :fichier

The controller testing is effected with the same pattern as follows (for each class):

post pictures_url, params: { picture: { fichier: file_fixture_upload("space_chen.jpg", "image/jpg"), individual: individuals(:one), shop_id: shops(:one).id, individual_id: individuals(:one).id } }, xhr: true
[...]
post documents_url, params: { document: { fichier: file_fixture_upload("find_shipment.pdf", "application/pdf"), title: 'title', shop_id: shops(:one).id, individual_id: individuals(:one).id } }, xhr: true

storage.yml configuration follows the prescribed:

test_fixtures:
  service: Disk
  root: <%= Rails.root.join("tmp/storage_fixtures") %>

Out of security space_chen.jpg and find_shipment.pdf files were added to the fixtures/files directory.

the fixtures/active_storage/attachments.yml set of fixtures is one are where the naming convention is opaque to this reader

document_fichier:
  name: find_shipment
  record: fichier (Document)
  blob: fichier_find_shipment_blob

picture_fichier:
  name: space_chen
  record: fichier (Picture)
  blob: fichier_space_chen_blob

while fixtures/active_storage/blobs.yml

fichier_find_shipment_blob: <%= ActiveStorage::FixtureSet.blob filename: "find_shipment.pdf", service_name: "test_fixtures" %>

fichier_space_chen_blob: <%= ActiveStorage::FixtureSet.blob filename: "space_chen.jpg", service_name: "test_fixtures" %>

In launching controller tests for either class, invariably the following error:

NoMethodError: undefined method `file_fixture_upload' for #<PicturesControllerTest:0x000000010ca46278>
[...]
NoMethodError: undefined method `file_fixture_upload' for #<DocumentsControllerTest:0x00000001082dac90>

The documentation starts out by stating:

  test "can sign up" do
    post signup_path, params: {
      name: "David",
      avatar: file_fixture_upload("david.png", "image/png")
    }

What is amiss?


Solution

  • Does it work if you use fixture_file_upload instead of file_fixture_upload?

    post api_v1_create_business_card_path, params: {
      front_image: fixture_file_upload('business-card.jpg', 'image/jpg'),
      back_image: fixture_file_upload('business-card.jpg', 'image/jpg'),
      language_hints: %w[en ja fr]
    },
    

    Like so: https://github.com/tonystrawberry/matomeishi-rails.jp/blob/main/spec/requests/api/v1/business_cards_spec.rb#L151

    Rails version: 7.0.8