How to Minitest Controller :create action with Paperclip Validators
Asked Answered
M

1

6

Basically my :create action test keeps failing, even though it works in the app. I commented out the paperclip validations in my controller below and it worked.

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

This is the test I am running, it works when the validations are commented out. How can i pass params that will meet the paperclip validations in my model.

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

FAILURE MESSAGE:

    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>'

Basically how do I make this test pass?

NOTE: I am aware that paperclip provides testing instructions with Shoulda and Spec was hoping to do this purely in Minitest.

Metanephros answered 10/6, 2015 at 6:49 Comment(0)
S
9

You should just attach an issue using ActionDispatch::TestProcess, fixture_file_upload. Put an image you want to use for your tests in test/fixtures adjust your test to look like this:

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

This will return an object that pretends to be an uploaded file for paperclip.

Stockdale answered 11/11, 2015 at 1:50 Comment(1)
Thanks that worked! I had tried fixture_file_upload before but i didn't specify the 'image/jpg' file type.Metanephros

© 2022 - 2024 — McMap. All rights reserved.