Rspec POST:创建测试失败的未定义方法`reject'为nil:NilClass?

时间:2015-12-23 23:03:56

标签: ruby ruby-on-rails-4 rspec factory-bot

我有一个Rails(4.1.8)应用程序与Rspec(3.1.0)和FactoryGirl(4.5.0)进行测试。我的控制器测试后创建操作失败,出现以下错误:

Failure/Error: post :create, { member_id: @member, fitness_goal: @fitness_goal_attributes }
 NoMethodError:
   undefined method `reject' for nil:NilClass

健身目标工厂:

FactoryGirl.define do

factory :fitness_goal do
association :goal_list
association :timeframe
start_date Date.current
end_date Date.current + 30
targets { [create(:target, outcome: "Lose Fat"), create(:target, outcome: "Reduce caloric intake by x%")] }
activities { [create(:activity, description: "Walk x steps a day"), create(:activity, description: "Climb x floors a day"), create(:activity, description: "Run x mile a day")] }   
association :member
association :trainer
notes 'This is a sample note.'
end
end

相关的FactoryGirl实例变量:

@fitness_goal_attributes = FactoryGirl.build(:fitness_goal).attributes

我在Fitness Goals Controller的创建动作中使用了数组拒绝方法:

def create
  unless params[:fitness_goal].blank? && params[:activity_ids].blank? && params[:target_ids].blank?
  params[:fitness_goal][:activity_ids] = params[:fitness_goal][:activity_ids].reject{ |activity_ids| activity_ids.empty? }   
  params[:fitness_goal][:target_ids] = params[:fitness_goal][:target_ids].reject{ |target_ids| target_ids.empty? }      
  @fitness_goal = @member.fitness_goals.build(fitness_goal_params)

  if @fitness_goal.save 
    flash[:success] = "Fitness goal was successfully created."
    redirect_to member_fitness_goals_path(@member)
  else
    render 'new'
  end
 end
end

健身目标参数:

def fitness_goal_params
  params.require(:fitness_goal).permit(:goal_list_id, :timeframe_id, :start_date, :end_date, { target_ids: [] }, { activity_ids: [] }, :notes, :member_id, :trainer_id)
 end

****编辑****** binding.pry / Better Errors的结果:

params[:fitness_goal][:activity_ids]
=> ["12", "10", "11"]

params[:fitness_goal][:target_ids]
=> ["1", "2"]

 params[:fitness_goal]
 => {"goal_list_id"=>"1", "timeframe_id"=>"2", "start_date"=>"2015-12-16", "end_date"=>"2016-01-15", "target_ids"=>["1", "2"], "activity_ids"=>["12", "10", "11"], "trainer_id"=>"", "notes"=>"testing"}

*****编辑*****

应用程序在开发和生产环境中按预期工作,但Rspec会为POST create方法的所有测试抛出错误。当我在数组上调用reject方法时,我无法弄清楚为什么除非语句没有充当“无保护”。我做错了什么以及如何解决错误?

1 个答案:

答案 0 :(得分:0)

我在你的代码中看到了2个错误,可以解释:

  1. 当您可能意味着使用&&

  2. 时,您使用||运算符
  3. 您检查params[:activity_ids]但请尝试使用params[:fitness_goal][:activity_ids]

  4. 所以你可以改变:

    unless params[:fitness_goal].blank? && params[:activity_ids].blank? && params[:target_ids].blank?
    

    由:

    unless params[:fitness_goal].blank? || params[:fitness_goal][:activity_ids].blank? || params[:fitness_goal][:target_ids].blank?