我在测试我的rails应用程序时遇到了一些麻烦。我只是在学习如何测试,所以我认为这对你来说应该没问题。 我有这个产品架构:
create_table "products", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "image_url"
t.decimal "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
这个模型:
class Product < ActiveRecord::Base
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
和这个控制器:
#some lines omitted...
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: @product }
else
format.html { render :new }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
private
def product_params
params.require(:product).permit(:title, :description, :image_url, :price)
end
所以,我正在进行这项测试:
setup do
@product = products(:one)
@update = {
title: 'Lorem Ipsum',
description: 'Wibbles are fun!',
image_url: 'lorem.jpg',
price: 19.95
}
end
test "should create product" do
assert_difference('Product.count') do
process :create, method: :post, params: @update
end
但我得到0次失败并出现1次错误。
Error:
ProductsControllerTest#test_should_create_product:
ActionController::ParameterMissing: param is missing or the value is empty: product
app/controllers/products_controller.rb:72:in `product_params'
app/controllers/products_controller.rb:27:in `create'
test/controllers/products_controller_test.rb:30:in `block (2 levels) in <class:ProductsControllerTest>'
test/controllers/products_controller_test.rb:29:in `block in <class:ProductsControllerTest>'
我必须说我只是将rails 4.2升级到5.0.0.1。我正在按照“使用rails 5进行敏捷开发”这本书的说法,但是如果我按照本书所说的那样进行测试就行不通了,我认为自从本书写完以来,rails已经改变了。 我试图在很多方面做到这一点,但我无法弄清楚。我究竟做错了什么?
感谢您的帮助!
答案 0 :(得分:2)
我的猜测是@update
必须看起来像这样
@update = {
product: {
title: 'Lorem Ipsum',
description: 'Wibbles are fun!',
image_url: 'lorem.jpg',
price: 19.95
}
}