【问题标题】:Rails tests lead to different results in apparently identical casesRails 测试在明显相同的情况下会导致不同的结果
【发布时间】:2021-04-12 06:03:15
【问题描述】:

以下类正在进行测试,带有一个夹具和测试断言。

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

运行此测试会返回错误,因为控制器会执行 .save!:

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

奇怪的是另一个类存在相同的模式并且相同的测试通过了。

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

两个上传器类都按照手动测试中的设计运行。

我只能推测类名和属性名之间存在一些混淆,但这是一个疯狂的假设,因为手动测试运行正常。

是什么导致了这个失败?应该如何解决?

【问题讨论】:

  • 你能分享测试吗?
  • 我不确定我是否理解这个问题。测试在问题中给出(每个组类的第三块)。验证错误是通过带有@image.save! 的控制器行生成的

标签: ruby-on-rails testing


【解决方案1】:

这可能是两件事之一 1-可能是命名约定,您是否尝试过将附件名称从image 更改为img 之类的名称? 2- 我看到Image 类和Attachment 类之间的区别,在使用的mount_uploader 中,一个使用DocumentUploader,另一个使用ImageUploader

抱歉,无法将这些放在评论中与您一起追踪,这里还是新的,只能使用答案。

【讨论】:

  • 我已经尝试过您的建议(尽管我过去没有遇到过这个命名问题)。将属性的名称更改为 ìmg` 仍然会导致验证错误ActiveRecord::RecordInvalid: Validation failed: Img can't be blank 它被称为类的事实指向某个地方......
猜你喜欢
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
相关资源
最近更新 更多