dimanche 11 avril 2021

Rails tests lead to different results in apparently identical cases

The following class is undergoing tests, with a fixture and the test assertions.

class Image < ApplicationRecord
  belongs_to :user, optional: true
  mount_uploader :image, ImageUploader
  validates :image, presence: true


create_me:
  brand_id: 1
  image: MyString
  caption: MyString


@image_create = images(:create_me)
assert_no_difference('Image.count') do
  post images_url, xhr: true, params: { image: {brand_id: @image_create.brand_id, image: @image_create.image } }
end

running this test returns an error, as the controller does a .save!:

ActiveRecord::RecordInvalid: Validation failed: Image can't be blank

The curious thing is the same pattern exists for another class and the same test passes.

class Attachment < ApplicationRecord
  belongs_to :user, optional: true
  mount_uploader :image, DocumentUploader
  validates :image, presence: true

create_me:
  brand_id: 1
  image: MyString
  caption: MyString

@attachment_create = attachments(:create_me)
assert_no_difference('Attachment.count') do
  post attachments_url, xhr: true, params: { attachment: { caption: @attachment_create.caption, brand_id: @attachment_create.brand_id, image: @attachment_create.image } }
end

Both uploader classes function as per design in manual tests.

I can only surmise some confusion between the class name and the attribute name, but that is a wild assumption, given manual tests run properly.

What is causing this failure? How should it be fixed?

Aucun commentaire:

Enregistrer un commentaire