我在使用Rspec 3和carrierwave时遇到一些问题,将图像保存到指定的测试目录。我一直在阅读文档,但我经常面对
Failure/Error: @uploader.store!(File.open("#{Rails.root}/spec/fixtures/yp2.jpg"))
NoMethodError:
undefined method `id' for nil:NilClass
# ./spec/rails_helper.rb:73:in `store_dir'
在
创建tmp路径/spec/uploads/tmp/
但图像未按预期保存在以下
/spec/uploads/animal_image/image/12
在rails_helper.rb
我有
# set test specific store directory
if defined?(CarrierWave)
CarrierWave::Uploader::Base.descendants.each do |klass|
next if klass.anonymous?
klass.class_eval do
def cache_dir
"#{Rails.root}/spec/support/uploads/tmp"
end
def store_dir
"#{Rails.root}/spec/support/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
end
end
和我的实际测试
require 'rails_helper'
require 'carrierwave/test/matchers'
describe AnimalImage do
include CarrierWave::Test::Matchers
before(:each) do
AnimalImageUploader.enable_processing = true
@uploader = AnimalImageUploader.new(@animal, :image)
@uploader.store!(File.open("#{Rails.root}/spec/fixtures/yp2.jpg"))
end
after(:each) do
@uploader.remove!
AnimalImageUploader.enable_processing = false
end
context 'Image Versions' do
it 'should scale large_animal_image to 555 x 365 ' do
expect(@uploader.large_animal_image).to have_dimensions(555, 365)
end
end
end
有没有人对为什么会发生这种情况有任何想法?
在进行一些调试时,我已经从我的规范
中捕获了@uploader对象 <AnimalImageUploader:0x00000002dafa28 @model=nil, @mounted_as=:image
如何设置模型?
因此,在收集了@rossta提供的评论后,我设法将图像保存在正确的位置以及图像的所有版本,但现在我只需要找到一个匹配器,告诉我版本每张图片都是正确的尺寸
before(:each) do
AnimalImageUploader.enable_processing = true
file = File.open("#{Rails.root}/spec/fixtures/yp2.jpg")
@animal = AnimalImage.create!(image: file)
@uploader = AnimalImageUploader.new(@animal, :image)
@uploader.store!
end
答案 0 :(得分:1)
在您的测试中,@animal
是模型,但您没有将其设置为任何值。尝试创建动物记录或实例化与id
等方法相对应的存根版本:
before(:each) do
AnimalImageUploader.enable_processing = true
@animal = Animal.create!
@uploader = AnimalImageUploader.new(@animal, :image)
@uploader.store!(File.open("#{Rails.root}/spec/fixtures/yp2.jpg"))
end