[英]ruby on rails - fixture_file_upload not working with controller tests for CarrierWave
I'm having a problem with my controller integration tests on my ROR 5.2 project using CarrierWave and Minitest. 我使用CarrierWave和Minitest对我的ROR 5.2项目的控制器集成测试有问题。 I'm using fixture_file_upload to "upload" a file, which works correctly in my model tests, but fails in my controller integration tests due to the presence validation of the CarrierWave property in my model.
我正在使用fixture_file_upload来“上传”一个文件,该文件在我的模型测试中正常工作,但由于我模型中CarrierWave属性的存在验证,我的控制器集成测试失败了。 It always fails on the create action.
它始终在创建操作上失败。 The update action occasionally and randomly fails too, even though I didn't update the CarrierWave property.
即使我没有更新CarrierWave属性,更新操作偶尔也会随机失败。
I used byebug to check the value of the property on the create action and it returns nothing; 我使用byebug来检查create动作的属性值,它什么都不返回; the property is never set.
该物业从未设定。 I also checked the errors of the newly created model and they are: "Icon can't be blank".
我还检查了新创建的模型的错误,它们是:“图标不能为空”。
fixture_file_upload works fine in my model tests, and doing the creating/updating/uploading manually (not in tests) works fine too. fixture_file_upload在我的模型测试中工作正常,手动创建/更新/上传(不在测试中)也可以正常工作。
I've Googled for many hours trying to figure out what I'm doing wrong, but everything I find says to use fixture_file_upload, and I haven't found anything related to the problem I'm having. 我用谷歌搜索了几个小时试图弄清楚我做错了什么,但我找到的所有内容都说使用了fixture_file_upload,我没有发现任何与我遇到的问题有关的内容。
CarrierWave initializer: CarrierWave初始化程序:
CarrierWave.configure do |config|
#To let CarrierWave work on heroku
config.root = Rails.root.join('tmp')
config.cache_dir = 'uploads/tmp'
if Rails.env.test? || Rails.env.development?
config.storage = :file
#config for tests is done in test/test_helper.rb
else
config.storage = :fog
config.fog_credentials = { #Configuration for Amazon S3
provider: 'AWS',
aws_access_key_id: Rails.application.credentials.aws[:access_key_id],
aws_secret_access_key: Rails.application.credentials.aws[:secret_access_key],
region: Rails.application.credentials.aws[:region]
}
config.fog_public = false
config.fog_directory = Rails.application.credentials.aws[:bucket_name]
config.fog_host = "#{Rails.application.credentials.aws[:asset_url]}/#{Rails.application.credentials.aws[:bucket_name]}"
end
end
Test helper: 测试助手:
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
include ActionDispatch::TestProcess #for fixture_file_upload
module UsersHelper
def login_as(user)
get login_user_url
assert_response :success
post user_login_url(session: { username: user.username, password: 'test1234' }) #have to hard code password here since passwords are stored encrypted
assert_redirected_to root_url, 'Login did not redirect'
end
def logout
get user_logout
end
end
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
end
class ActionDispatch::IntegrationTest
include UsersHelper
end
#setup carrierwave for tests
carrierwave_root = Rails.root.join('tmp', 'test', 'support', 'carrierwave')
carrierwave_template = Rails.root.join('test', 'fixtures', 'files')
CarrierWave.configure do |config|
config.root = carrierwave_root
config.cache_dir = carrierwave_root.join('carrierwave_cache')
config.enable_processing = false
end
#copy carrierwave fixture files to carrierwave root
puts 'Copying CarrierWave fixture files..'
puts carrierwave_template.join('uploads')
puts carrierwave_root
FileUtils.cp_r carrierwave_template.join('uploads'), carrierwave_root
Minitest.after_run do
#remove carrierwave files
puts 'Deleting CarrerWave fixture files...'
Dir.glob(Pathname.new(carrierwave_root).join('*')).each do |dir|
FileUtils.remove_entry(dir)
end
puts 'Cleaning CarrierWave cached files...'
CarrierWave.clean_cached_files!(0)
end
Model: 模型:
class Category < ApplicationRecord
mount_uploader :icon, IconUploader, dependent: :destroy
validates :name, length: { minimum: 2, maximum: 30 }, uniqueness: { case_sensitive: false }
validates :slug, length: { minimum: 2, maximum: 30 }, uniqueness: { case_sensitive: false }
validates :icon, presence: true
end
IconUploader: IconUploader:
class IconUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
after :remove, :delete_empty_upstream_dirs
def store_dir
"#{base_store_dir}/#{model.id}"
end
def base_store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}"
end
#override file name, for uniqueness
def filename
random_token = SecureRandom.hex(6/2) #length of 6 characters
token_var = "@#{mounted_as}_secure_token" #get token variable name
token = model.instance_variable_get(token_var) #get token from token variable name
token ||= model.instance_variable_set(token_var, random_token) #if token isn't already set, set it
@name ||= "#{token}_#{super}" if original_filename.present? and super.present? #create name, using instance variable so token isn't changed (function is called multiple times)
end
#set size limits
def size_range
1.kilobyte..256.kilobytes #1 kilobyte to 256 kilobytes
end
#resize image if width or height is greater than 256px, add padding if needed
process resize_and_pad: [256, 256] #don't use resize_to_fit, as it adds a white background at least to SVG images
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_whitelist
%w(jpg jpeg png svg)
end
#whitelist of content types
def content_type_whitelist
/image\// #whitelist images
end
private
#delete directory if it's empty
def delete_empty_upstream_dirs
path = ::File.expand_path(store_dir, root)
Dir.delete(path) #fails if path not empty dir
path = ::File.expand_path(base_store_dir, root)
Dir.delete(path) #fails if path not empty dir
rescue SystemCallError => e
Rails.logger.error(e.message) #log error
true #nothing, the dir is not empty
end
end
Controller create action: 控制器创建动作:
def create
data = params.require(:category).permit([ :name, :icon, :icon_cache ])
@category = Category.new(data)
if @category.save
flash.notice = 'Category successfully created.'
redirect_to categories_path
else
render :add #show errors
end
end
Controller test: 控制器测试:
test "should post category_create when admin" do
login_as(users(:admin))
get add_category_url
assert_response :success
icon = fixture_file_upload(Rails.root.join('test', 'fixtures', 'files', 'category_icon.svg'))
#fails: validation error: "Icon can't be blank"
post category_create_url(category: { name: 'test901', icon: icon, icon_cache: '' })
assert_redirected_to categories_url
assert_equal 'Category successfully created.', flash[:notice]
end
Model test: 型号测试:
test "should save when all details correct" do
category = Category.new(name: 'tools',
icon: fixture_file_upload(Rails.root.join('test', 'fixtures', 'files', 'category_icon.svg')))
#succeeds
assert category.save, 'Not saved when all details correct: ' + category.errors.full_messages.to_s
end
post category_create_url(category: { name: 'test901', icon: icon, icon_cache: '' })
should be 应该
post category_create_url, params: {category: { name: 'test901', icon: icon, icon_cache: '' }}
The first is sending params to the route_helper and results in an attempt to pass the file through query string parameters which won't work. 第一个是将params发送到route_helper并导致尝试通过查询字符串参数传递文件,这些参数将无效。
The second sends params to the post method which correctly posts the params as multipart/form data which will correctly post the file object to the controller. 第二个向post方法发送params,它将params正确地发布为multipart / form数据,这将正确地将文件对象发布到控制器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.