如何使用RSpec进行正确的关联测试?

问题描述

在我的应用程序中,我有一个名为 License 的模型。这些是该模型的以下关联:

  # Associations
  belongs_to :user
  has_one_attached :file

然后在我写的spec.rb文件中,该许可证专用于用户,如下所示:

describe 'when testing associations' do
    it { is_expected.to belong_to :user }
  end

我收到了我的期望:

测试关联时的许可 应该属于用户要求:true

然后我尝试对另一个关联进行相同的操作:

it { is_expected.to has_one_attached :file }

我得到以下回报:

** 1)测试关联时的许可 失败/错误:它{is_expected.to has_one_attached:file}

 NoMethodError:
   undefined method `has_one_attached' for #<RSpec::ExampleGroups::License::WhenTestingAssociations:0x00000000086ccf48>
 # ./spec/models/license_spec.rb:10:in `block (3 levels) in <top (required)>'**

为什么会这样,我该如何解决?

解决方法

has_one_attached 

它不是活动记录关联类型,它与活动存储相关,您仍然可以按以下方式进行测试

describe 'Attachment' do
  before do
    subject.
      file.
      attach(
        io: File.open(fixture_path + '/dummy_image.jpg'),filename: 'attachment.jpg',content_type: 'image/jpg'
      )
  end

  it 'is valid  ' do
    expect(subject.file).to be_attached
  end
end

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...