我正在尝试测试基本的create操作。我有一个模型MealPlan
,其中has_many :dinners, through: :meals
。用户可以为一周创建一个MealPlan,将在特定的晚餐中添加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
这将在餐食计划控制器中调用create方法:
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个晚餐的固定装置,在设置这些测试时就可以使用。
在某些情况下,这是餐_计划.rb,再次与众不同:
class MealPlan < ApplicationRecord
belongs_to :user
has_many :meals
has_many :dinners, through: :meals
end
我正在尝试测试基本的create操作。我有一个MealPlan模型,通过::meals具有has_many:dinners。用户可以为一周创建一个MealPlan,将在特定的晚餐中添加7顿饭。 ...
请尝试以下方法: