我无法通过集成测试。用户创建可以具有许多图片的产品。产品的new.html.erb
包含文件字段<%= file_field_tag "images[]", type: :file, multiple: true %>
代码工作正常,我只是在创建工作集成测试时遇到问题。
products_creation_test.rb:
require 'test_helper'
class ProductsCreationTest < ActionDispatch::IntegrationTest
.
.
.
test "should create new product with valid info" do
log_in_as(@user)
pic1 = fixture_file_upload('test/fixtures/cat1.jpg', 'image/jpg')
pic2 = fixture_file_upload('test/fixtures/profile.png', 'image/png')
assert_difference 'Product.count', 1 do
post user_products_path(@user), product: { title: 'test',
description: 'test',
price: '5.99',
images: [pic1, pic2] }
end
assert_redirected_to @user
@user.reload
newprod = @user.products.last
pics = newprod.pictures.all
assert_equal 2, pics.count
end
end
这失败了最后一个断言,声明没有与新产品相关的图片,当应该有2.检查pics
变量时,我收到以下错误:RuntimeError: #<ActiveRecord::AssociationRelation []
我错过了什么?
我的模型结构如下:
User
has_many Products
,Products
has_many Pictures
products_controller.rb:
class ProductsController < ApplicationController
before_action :valid_user, only: [:new, :create, :edit, :update]
.
.
.
def create
@product = current_user.products.build(product_params)
if @product.save
# to handle multiple images upload on create
if params[:images]
params[:images].each { |image|
@product.pictures.create(image: image)
}
end
flash[:success] = "Product Created!"
redirect_to current_user
else
flash[:alert] = "Something went wrong."
render :new
end
end
.
.
.
end
pictures_controller.rb:
class PicturesController < ApplicationController
def create
@picture = Picture.new(picture_params)
@picture.save
end
def destroy
end
private
def picture_params
params.require(:picture).permit(:product_id, :image, :_destroy)
end
end
picture.rb:
class Picture < ActiveRecord::Base
belongs_to :product
mount_uploader :image, PicturesUploader
validates_integrity_of :image
validates_processing_of :image
validates :image, file_size: { less_than: 10.megabytes }
end
答案 0 :(得分:1)
解决方法如下:
修订了products_creation_test.rb:
require 'test_helper'
class ProductsCreationTest < ActionDispatch::IntegrationTest
.
.
.
test "should create new product with valid info" do
log_in_as(@user)
pic1 = fixture_file_upload('test/fixtures/cat1.jpg', 'image/jpg')
pic2 = fixture_file_upload('test/fixtures/profile.png', 'image/png')
assert_difference 'Product.count', 1 do
post user_products_path(@user), product: { title: 'test',
description: 'test',
price: '5.99',
}, images: [pic1, pic2]
end
assert_redirected_to @user
newprod = assigns(:product)
assert_equal 2, newprod.pictures.count
end
end