如何最小化控制器:使用回形针验证器创建操作

How to Minitest Controller :create action with Paperclip Validators

基本上我的 :create 动作测试总是失败,即使它在应用程序中有效。我在下面的控制器中注释掉了回形针验证并且它起作用了。

  has_attached_file :image, styles: { medium: "700x700>", small: "350x250#" }
  validates_attachment_presence :image
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/

这是我的测试 运行,当验证被注释掉时它会起作用。我如何传递满足模型中回形针验证的参数。

test "should create if signed_in" do
      sign_in(@user)
      assert_difference 'Product.count' do
        post :create, product:{ title:'test_product', description: 'khara', user_id: @user.id}
      end
      assert_redirected_to product_path(assigns(:product))
    end

失败消息:

    FAIL["test_should_post_create_if_signed_in", ProductsControllerTest, 0.58458]
         test_should_post_create_if_signed_in#ProductsControllerTest (0.58s)
                "Product.count" didn't change by 1.
                Expected: 3
                  Actual: 2
                test/controllers/products_controller_test.rb:52:in `block in <class:ProductsControllerTest>'

基本上我该如何通过这个测试?

注意:我知道回形针提供了 Shoulda 的测试说明,而 Spec 希望纯粹在 Minitest 中做到这一点。

您应该使用 ActionDispatch::TestProcess、fixture_file_upload 附加问题。在 test/fixtures 中放置一张你想用于测试的图像 将你的测试调整为如下所示:

test "should create if signed_in" do
          sign_in(@user)
          image = fixture_file_upload('some_product_image.jpg', 'image/jpg')
          assert_difference 'Product.count' do
            post :create, product:{ title:'test_product', 
                               description: 'khara', 
                                   user_id: @user.id,
                                     image: image
                                   }
          end
          assert_redirected_to product_path(assigns(:product))
        end

这将 return 一个伪装成回形针上传文件的对象。