作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我刚刚改用 Rails 5.1.4 上的 ActiveStorage,我是 TDD 的新手,正在努力弄清楚如何测试 has_one_attached :avatar
的模型。
require 'rails_helper'
RSpec.describe User, :type => :model do
let (:valid_user) { FactoryBot.build(:user) }
describe "Upload avatar" do
context "with a valid image" do
it "saves the image" do
valid_user.save!
saved_file = valid_user.avatar.attach(io: File.open("/home/ubuntu/workspace/spec/fixtures/files/avatar.jpg"), filename: "face.jpg", content_type: "image/jpg")
expect(saved_file).to be_an_instance_of(ActiveStorage::Attachment::One)
end
end
end
end
Failures:
1) User Upload avatar with a valid image saves the image
Failure/Error:
saved_file = valid_user.avatar.attach(io: File.open("/home/ubuntu/workspace/spec/fixtures/files/avatar.jpg"), filename: "face.jpg",
content_type: "image/jpg")
NoMethodError:
undefined method `upload' for nil:NilClass
Did you mean? load
# /usr/local/rvm/gems/ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/blob.rb:48:in `upload'
# /usr/local/rvm/gems/ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/blob.rb:21:in `block in build_after_upload'
# /usr/local/rvm/gems/ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/blob.rb:16:in `tap'
# /usr/local/rvm/gems/ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/blob.rb:16:in `build_after_upload'
# /usr/local/rvm/gems/ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/blob.rb:26:in `create_after_upload!'
# /usr/local/rvm/gems/ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/attached.rb:25:in `create_blob_from'
# /usr/local/rvm/gems/ruby-2.3.4/gems/activestorage-0.1/lib/active_storage/attached/one.rb:9:in `attach'
# ./spec/models/user_spec.rb:47:in `block (4 levels) in <top (required)>'
最佳答案
我解决了使用
FactoryBot.define do
factory :culture do
name 'Soy'
after(:build) do |culture|
culture.image.attach(io: File.open(Rails.root.join('spec', 'factories', 'images', 'soy.jpeg')), filename: 'soy.jpeg', content_type: 'image/jpeg')
end
end
end
describe '#image' do
subject { create(:culture).image }
it { is_expected.to be_an_instance_of(ActiveStorage::Attached::One) }
end
关于ruby-on-rails - 如何在 Rails 中使用 ActiveStorage 正确进行模型测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47583883/
我是一名优秀的程序员,十分优秀!