[英]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. 我使用Rails 5.1,在进行简单的控制器测试时遇到了一些麻烦。
I created a pretty standard Rails App with scaffolding: 我用脚手架创建了一个非常标准的Rails应用程序:
rails g scaffold Product title:string description:text image_url:string price:decimal rails g scaffold产品名称:字符串描述:文本image_url:字符串价格:小数
All the CRUD operations are working as expected. 所有CRUD操作均按预期进行。
But my controller test is causing me an headache: 但是我的控制器测试让我头疼:
I have the referenced test image files in my app/assets/images folder. 我的app / assets / images文件夹中有引用的测试图像文件。
In test/controllers/products_controller_test.rb: 在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: 在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: 在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? 我该如何解决?
' rails.png '
doesn't satisfy the format for your image_url
validation, check here . ' rails.png '
不符合您的image_url
验证格式,请点击此处 。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.