Rails 控制器内 json 对象中不存在 4 个集成测试数组
Rails 4 Integration Testing Arrays not present in json object inside controllers
我正在尝试为创建名为 books 的记录创建集成测试。我在测试中创建哈希时遇到问题。这是我的代码:
test/integration/creating_book_test.rb
require 'test_helper'
class CreatingBookTest < ActionDispatch::IntegrationTest
def setup
@michael_lewis = Author.create!(name: 'Michael Lewis')
@business = Genre.create!(name: 'Business')
@sports = Genre.create!(name: 'Sports')
@analytics = Genre.create!(name: 'Analytics')
end
test "book is created successfully" do
post '/api/books', { book: book_attributes }.to_json, {
'Accept' => 'application/json',
'Content-Type' => 'application/json'
}
... assertions...
end
def book_attributes
{title: 'Moneyball',
year: 2003,
review: 'Lorem Ipsum',
rating: 5,
amazon_id: '10832u13kjag',
author_ids: [@michael_lewis.id],
genre_ids: [@business.id, @sports.id, @analytics.id]
}
end
end
在控制器中,我将参数列入白名单:
def book_params
params.require(:book).permit(:title, :year, :review, :rating, :amazon_id, :author_ids, :genre_ids)
end
问题是我在控制器中没有收到 :author_ids 和 :genre_ids。似乎数组没有发送到控制器,所以我无法测试关联是否正常工作。
谢谢。
你强参数声明错误。这是修复:
params.require(:book).permit(:title, :year, :review, :rating, :amazon_id, author_ids: [], genre_ids: [])
来自 Permitted Scalar Values 文档:
..To declare that the value in params must be an array of permitted scalar values map the key to an empty array.
我正在尝试为创建名为 books 的记录创建集成测试。我在测试中创建哈希时遇到问题。这是我的代码:
test/integration/creating_book_test.rb
require 'test_helper'
class CreatingBookTest < ActionDispatch::IntegrationTest
def setup
@michael_lewis = Author.create!(name: 'Michael Lewis')
@business = Genre.create!(name: 'Business')
@sports = Genre.create!(name: 'Sports')
@analytics = Genre.create!(name: 'Analytics')
end
test "book is created successfully" do
post '/api/books', { book: book_attributes }.to_json, {
'Accept' => 'application/json',
'Content-Type' => 'application/json'
}
... assertions...
end
def book_attributes
{title: 'Moneyball',
year: 2003,
review: 'Lorem Ipsum',
rating: 5,
amazon_id: '10832u13kjag',
author_ids: [@michael_lewis.id],
genre_ids: [@business.id, @sports.id, @analytics.id]
}
end
end
在控制器中,我将参数列入白名单:
def book_params
params.require(:book).permit(:title, :year, :review, :rating, :amazon_id, :author_ids, :genre_ids)
end
问题是我在控制器中没有收到 :author_ids 和 :genre_ids。似乎数组没有发送到控制器,所以我无法测试关联是否正常工作。
谢谢。
你强参数声明错误。这是修复:
params.require(:book).permit(:title, :year, :review, :rating, :amazon_id, author_ids: [], genre_ids: [])
来自 Permitted Scalar Values 文档:
..To declare that the value in params must be an array of permitted scalar values map the key to an empty array.