Rails 5集成测试将fixture_file_upload转换为字符串

时间:2017-09-07 21:58:19

标签: testing ruby-on-rails-5

的Env
导轨:5.1.3
Ruby:2.3.1p112

上下文
我有一个基本的集成测试如下:

class MerchandisesControllerTest < ActionDispatch::IntegrationTest
  def test_successful_create
    post org_merchandises_path(org, merchandise: merchandise_params)

    ...
  end

  def merchandise_params
    {
      description: 'Get swole fast.',
      name: 'Foo Powder',
      price: 50,
      images_attributes: {
        '0' => {
          image:   fixture_file_upload('files/image.png', 'image/png'),
          primary: true,
        }
      }
    }
  end
end

当我运行测试时,图像参数将转换为String

# Inside MerchandisesController#create

params.dig(:merchandise, :images_attributes, '0', :image)
=> "#<Rack::Test::UploadedFile:0x007fbdc9520b00>"
# This is a String, but should instance of ActionDispatch::Http::UploadedFile

可能的相关问题
https://github.com/rails/rails/issues/28129

1 个答案:

答案 0 :(得分:-1)

由于某些原因,以下列方式使用post方法无法正确序列化/反序列化图像参数:

# Fails to properly serialize file param
post org_merchandises_path(org, merchandise: merchandise_params)

你必须这样做:

# Properly serializes the file param
post org_merchandises_path(org), params: { merchandise: merchandise_params }

我不知道为什么。似乎它应该双向工作,但事实并非如此。