通过关联创建带有 has_many 的动作测试
Create action test with a has_many through association
我正在尝试测试基本的创建操作。我有一个模型 MealPlan
has_many :dinners, through: :meals
。用户可以为一周创建一个膳食计划,这将添加 7 餐和特定的晚餐。这行得通。
不过我在测试时遇到了问题。
setup do
@user = users(:travis)
sign_in @user
end
test "should create a mealplan" do
post meal_plans_url, params: { meal_plan: {dinner_ids: [1, 2, 3, 4, 5, 6, 7],
weekof: Date.today.beginning_of_week.next_week }}
assert_redirected_to meal_plan_path(MealPlan.last)
end
end
这会调用 meal_plans_controller:
中的创建方法
def create
@meal_plan = current_user.meal_plans.build(meal_plan_params)
respond_to do |format|
if @meal_plan.save!
format.html { redirect_to @meal_plan, notice: 'Dinner was successfully created.' }
else
...
end
end
end
我认为非常简单,但每当我尝试在测试中保存它时,我都会收到此错误:
ActiveRecord::RecordInvalid: Validation failed: Dinners is invalid
(我在 save
上添加了砰砰声以查看发生了什么)。
另外,我有 7 个晚餐的固定装置,当我设置这些测试时我可以访问它们。
这是某些上下文的 meal_plan.rb,同样没有异常:
class MealPlan < ApplicationRecord
belongs_to :user
has_many :meals
has_many :dinners, through: :meals
end
请试试这个:
params: { meal_plan: { dinner_ids: Dinner.where(id: [1, 2, 3, 4, 5, 6, 7]), weekof: Date.today.beginning_of_week.next_week }}
我认为您在参数转换中漏掉了一些东西,所以试试这个,我想您会解决问题的。
更新
PS。我很高兴我们弄明白了:-)我希望你也明白发生了什么事;-)
我正在尝试测试基本的创建操作。我有一个模型 MealPlan
has_many :dinners, through: :meals
。用户可以为一周创建一个膳食计划,这将添加 7 餐和特定的晚餐。这行得通。
不过我在测试时遇到了问题。
setup do
@user = users(:travis)
sign_in @user
end
test "should create a mealplan" do
post meal_plans_url, params: { meal_plan: {dinner_ids: [1, 2, 3, 4, 5, 6, 7],
weekof: Date.today.beginning_of_week.next_week }}
assert_redirected_to meal_plan_path(MealPlan.last)
end
end
这会调用 meal_plans_controller:
中的创建方法 def create
@meal_plan = current_user.meal_plans.build(meal_plan_params)
respond_to do |format|
if @meal_plan.save!
format.html { redirect_to @meal_plan, notice: 'Dinner was successfully created.' }
else
...
end
end
end
我认为非常简单,但每当我尝试在测试中保存它时,我都会收到此错误:
ActiveRecord::RecordInvalid: Validation failed: Dinners is invalid
(我在 save
上添加了砰砰声以查看发生了什么)。
另外,我有 7 个晚餐的固定装置,当我设置这些测试时我可以访问它们。
这是某些上下文的 meal_plan.rb,同样没有异常:
class MealPlan < ApplicationRecord
belongs_to :user
has_many :meals
has_many :dinners, through: :meals
end
请试试这个:
params: { meal_plan: { dinner_ids: Dinner.where(id: [1, 2, 3, 4, 5, 6, 7]), weekof: Date.today.beginning_of_week.next_week }}
我认为您在参数转换中漏掉了一些东西,所以试试这个,我想您会解决问题的。
更新
PS。我很高兴我们弄明白了:-)我希望你也明白发生了什么事;-)