2017-09-29 5 views
1

私はRails 5.1を使用しており、単純なコントローラテストではいくつか問題があります。Rails 5.1 ControllerTestはフロントエンドで動作していても新しいエントリを作成しません

私は足場とかなり標準のRailsアプリケーションを作成しました:文字列の説明:テキスト IMAGE_URL:文字列価格:すべてのCRUD操作のように働いている

10進

はグラム足場製品のタイトルをレール期待される。

しかし、私のコントローラのテストは私に頭痛を引き起こしている:

私は私のアプリ/資産/画像フォルダの参照テスト画像ファイルを持っています。

テスト/コントローラ/ products_controller_test.rbで

:テスト/フィクスチャ/ファイル/ products.ymlで

class Product < ApplicationRecord 
    validates :title, :description, :image_url, presence: true 
    validates :price, numericality: {greater_than_or_equal_to: 0.01} 
    validates :title, uniqueness: true 
    validates :image_url, allow_blank: true, format: { 
    with: %r{\.(gif|jpg|png)\Z}i, 
    message: 'must be a URL for GIF, JPG or PNG image.' 
    } 
end 

:アプリ/モデル/ product.rbで

require 'test_helper' 

class ProductsControllerTest < ActionDispatch::IntegrationTest 
    setup do 
    @product = products(:one) 
    @update = { 
     title:  ' Lorem ipsum  ', 
     description: ' Rails is great! ', 
     image_url: ' rails.png  ', 
     price:  19.99 
    } 
    end 

    test "should create product" do 
    assert_difference('Product.count') do 
     post products_url, params: { product: @update } 
    end 

    assert_redirected_to product_url(Product.last) 
    end 
end 

one: 
    title: MyString 
    description: MyText 
    image_url: rails.png 
    price: 9.99 

two: 
    title: Foo 
    description: Bar 
    image_url: MyString.png 
    price: 9.99 

エラーメッセージは次のとおりです。

Failure: 
ProductsControllerTest#test_should_create_product [myapp/test/controllers/products_controller_test.rb:25]: 
"Product.count" didn't change by 1. 
Expected: 3 
    Actual: 2 

私のテストでは新しい製品のエントリを作成できないようです。どうすれば修正できますか?

答えて

2

' rails.png 'は、image_urlの検証のフォーマットを満たしていないため、hereにチェックを入れてください。

製品の新しいレコードを作成する予定の場合は、空白を削除するか、正規表現を変更することを検討してください。この方法でうまくいく:

@update = { 
    title:  ' Lorem ipsum  ', 
    description: ' Rails is great! ', 
    image_url: 'rails.png', 
    price:  19.99 
} 
関連する問題