ruby-on-rails RSpec请求规范,以使用FactoryBot测试ActiveStorage

klsxnrf1  于 5个月前  发布在  Ruby
关注(0)|答案(1)|浏览(44)

我在网上阅读了许多问答和帖子,尝试了每一个建议的解决方案,但没有找到一个使用ActiveStorage和FactoryBot进行RSpec请求测试的有效解决方案。
到目前为止,我已经了代码

# factories/user.rb

factory :registered_user, :class => User do
  sequence(:email) { |n| "foobar_#{n}@email.com" }
  ...

  factory :invalid_user, :class => User do
    email { '!!!' }
    ...

    # I'm trying to make this (or similar) to work
    picture { Rack::Test::UploadedFile.new(Rails.root.join('spec/factories/files/pictures/image-INVALID-size-too-big.jpg'), 'image/jpeg') }
  end
end

个字符
通过运行上述规范,我得到了错误

ActiveSupport::MessageVerifier::InvalidSignature: mismatched digest


"日志"
...运行上述规范时:

Started PATCH "/users/image?user%5Bpicture%5D=%23%3CRack%3A%3ATest%3A%3AUploadedFile%3A0x0000000122758d98%3E" for 127.0.0.1 at 2024-01-09 09:07:41 +0100
[ActiveJob] Enqueued ActiveStorage::AnalyzeJob (Job ID: 835acb7e-3d89-45b5-9f1e-be2ab4f7b9cd) to Test(default) with arguments: #<GlobalID:0x000000012108d488 @uri=#<URI::GID gid://my-app/ActiveStorage::Blob/95>>
  Processing by Users::ImagesController#update as HTML
  Parameters: {"user"=>{"picture"=>"#<Rack::Test::UploadedFile:0x0000000122758d98>"}}


...在浏览器中 * 手动 * 上传文件时:

Started PATCH "/users/image" for 127.0.0.1 at 2024-01-09 07:03:08 +0100
  Processing by Users::ImagesController#update as HTML
  Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"picture"=>#<ActionDispatch::Http::UploadedFile:0x0000000121786190 @tempfile=#<Tempfile:/var/folders/74/bpsjzpcx73vd5601bgrny37w0000gn/T/RackMultipart20240109-45321-1ccx6n.jpg>, @content_type="image/jpeg", @original_filename="image-INVALID-size-too-big", @headers="Content-Disposition: form-data; name=\"user[picture]\"; filename=\"image-INVALID-size-too-big\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Update picture"}


如何让事情运转起来?

w1jd8yoj

w1jd8yoj1#

参数必须进入patch,而不是url助手:

let(:invalid_user_params) {
  # permitted params are on the other side of the request, not here
  {picture: Rack::Test::UploadedFile.new(Rails.root.join("spec/test.png"), "image/png")}
}

it "status :unprocessable_entity" do
  #                       v
  patch(users_image_path, params: {user: invalid_user_params})
  expect(response).to have_http_status(:unprocessable_entity)
end

字符串

  • 网址:http://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html#method-i-patch*

相关问题