假设您对模型用户进行了测试,默认为UserTest#test_the_truth
rails test test/models/user_test.rb
我想你遇到了一个错误
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 中删除头像列并添加两个新文件:
(免责声明另见下面的 cmets:“无需创建自己的模型,因此您可以使用原始的 ActiveStorage::Attachment 代替 ActiveStorage::Attachment 并将夹具放在 active_storage 文件夹下”,另请参阅 @987654321 @)
# 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,应该会找到一些测试生成的文件夹和文件。
在 cmets 之后编辑:
如果您需要在 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
我不知道你的回调,但我希望这能给你一些提示。