Activestorage固定装置附件
在铁轨测试中。 我有一个只有activestorage的基本模型:
class User < ApplicationRecord has_one_attached :avatar end
我正试图让它成为固定装置,但没有运气(我确实有一个图像):
# users.yml one: avatar:
如何通过灯具正确附加头像文件?
假设您对模型用户进行了测试,默认的UserTest#test_the_truth
rails test test/models/user_test.rb
我想你得到一个错误Errno::ENOENT: No such file or directory @ rb_sysopen
测试期间Errno::ENOENT: No such file or directory @ rb_sysopen
,因为路径中的错误,你必须添加'fixtures'
,它应该是这样的:
# users.yml one: name: 'Jim Kirk' avatar: <%= File.open Rails.root.join('test', 'fixtures', 'files', 'image.png').to_s %>
但现在你应该有这个错误: ActiveRecord::Fixture::FixtureError: table "users" has no column named "avatar".
这是正确的,因为ActiveStorage使用两个表来工作: active_storage_attachments
和active_storage_blobs
。
因此,您需要从users.yml
删除头像列并添加两个新文件:
# active_storage_attachments.yml one: name: 'avatar' record_type: 'User' record_id: 1 blob_id: 1
和
# active_storage_blobs.yml one: id: 1 key: '12345678' filename: 'file.png' content_type: 'image/png' metadata: nil byte_size: 2000 checksum: "123456789012345678901234"
此外,在App/models
, 即使ActiveStorage不需要 , 也要添加。
# active_storage_attachment.rb class ActiveStorageAttachment < ApplicationRecord end
和
# active_storage_blob.rb class ActiveStorageBlob < ApplicationRecord end
然后UserTest#test_the_truth
成功。
但最好摆脱 active_storage_attachment.rb
和active_storage_blob.rb
并按照另一种方式进行测试。
要测试附件是否正常工作,请更好地测试控制器 ,例如在test/controllers/users_controller_test.rb
添加此代码:
require 'test_helper' class UserControllerTest < ActionController::TestCase def setup @controller = UsersController.new end test "create user with avatar" do user_name = 'fake_name' avatar_image = fixture_file_upload(Rails.root.join('test', 'fixtures', 'files', 'avatar.png'),'image/png') post :create, params: {user: {name: user_name, avatar: avatar_image}} end end
检查文件夹tmp/storage
,应为空。
使用: rails test test/controllers/users_controller_test.rb
启动测试
它应该成功,然后如果再次检查tmp/storage
,你应该找到测试生成的一些文件夹和文件。
评论后编辑:如果您需要测试User
模型上的回调,那么这应该有效:
# rails test test/models/user_test.rb require 'test_helper' class UserTest < ActiveSupport::TestCase test "should have avatar attached" do u = User.new u.name = 'Jim Kirk' file = Rails.root.join('test', 'fixtures', 'files', 'image.png') u.avatar.attach(io: File.open(file), filename: 'image.png') # attach the avatar, remove this if it is done with the callback assert u.valid? assert u.avatar.attached? # checks if the avatar is attached end end
我不知道你的回调,但我希望这会给你一些提示。