如何使用最小控制器:使用Paperclip验证器创建操作

Chi*_*ris 5 model-view-controller ruby-on-rails paperclip minitest

基本上我的:创建动作测试保持失败,即使它在应用程序中工作.我在下面的控制器中注释了回形针验证并且它有效.

  has_attached_file :image, styles: { medium: "700x700>", small: "350x250#" }
  validates_attachment_presence :image
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
Run Code Online (Sandbox Code Playgroud)

这是我正在运行的测试,它在注释验证时有效.我怎样才能通过符合我模型中回形针验证的参数.

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
Run Code Online (Sandbox Code Playgroud)

失败的消息:

    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>'
Run Code Online (Sandbox Code Playgroud)

基本上我该怎么做这个测试通过?

注意:我知道回形针提供了测试指令,而Shoulda和Spec希望纯粹在Minitest中做到这一点.

小智 7

您应该使用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
Run Code Online (Sandbox Code Playgroud)

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