StandardNerd
StandardNerd

Reputation: 4183

Rails 5.1 ControllerTest doesn't create new entry even though in frontend it works

I use Rails 5.1 and have some trouble with a simple Controller Tests.

I created a pretty standard Rails App with scaffolding:

rails g scaffold Product title:string description:text image_url:string price:decimal

All the CRUD operations are working as expected.

But my controller test is causing me an headache:

I have the referenced test image files in my app/assets/images folder.

In test/controllers/products_controller_test.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

In app/models/product.rb:

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

In test/fixtures/files/products.yml:

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

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

The error message I'm getting is:

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

It looks like my test can't create new product entries. How can I fix it?

Upvotes: 1

Views: 117

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

' rails.png ' doesn't satisfy the format for your image_url validation, check here.

If you're expecting to create a new record for product, then consider removing the whitespaces, or adapting your regular expression. This way it'd work:

@update = {
  title:       ' Lorem ipsum     ',
  description: ' Rails is great! ',
  image_url:   'rails.png',
  price:       19.99
}

Upvotes: 2

Related Questions