jeudi 1 juin 2017

How to pass RSpec controller testing for POST request on associated models for Rails-React?

I am using Rails-API; I have React front-end and Rails back-end. I am writing test for my POST create using RSpec and I am having trouble making it pass.

The model involved is schedule and worker. Schedule has many workers and worker belongs to schedule.

Here are some of the code snippets:

  //schedules_controller.rb
  def create
    @schedule = Schedule.new(schedule_params)

    if @schedule.save
      worker_params["worker_info"].each do |w|
        @schedule.workers.create!(w)
      end
     render json: @schedule
    else
     render json: @schedule, status: :unprocessable_entity
    end
  end

  ...

  def schedule_params
    params.require(:schedule).permit(:date, :message, :user_id)
  end

  def worker_params
    params.permit(worker_info: [:name, :phone])
  end

It is a little complicated, but I can assure that it works. React sends an array of workers info (name and phone) and be associated to schedule. Here is what it looks like on Rails server log:

  Parameters: {"date"=>"2017-06-01T17:35:30.000Z", "message"=>"Heya Workers!", "user_id"=>1, "worker_info"=>[{"name"=>"Arvel Sauer
", "phone"=>"1234567890"}, {"name"=>"Celia Grant PhD", "phone"=>"1234567890"}], "schedule"=>{"date"=>"2017-06-01T17:35:30.000Z", "
user_id"=>1, "message"=>"Heya Workers!"}}

My RSpec for schedules controller is such:

RSpec.describe SchedulesController do
  num_schedule = 3
  num_worker = 10
  let(:schedule) {FactoryGirl.create(:schedule)}
  worker_info = [{name: "Test1", phone: "(123-456-7890)"}]

  before (:each) do
    FactoryGirl.create_list(:schedule, num_schedule)
  end

  describe "POST create" do
    it "adds new schedule by 1" do
      FactoryGirl.create(:worker)
      expect {
        post "/api/schedules", schedule: {date: schedule.date, user_id: schedule.user_id, message: schedule.message}
      }.to change(Schedule, :count).by(1)
    end
  end
  ...

The error that I get:

  1) SchedulesController POST create adds new schedule by 1
     Failure/Error:
       worker_params["worker_info"].each do |w|
         @schedule.workers.create!(w)
       end

     NoMethodError:
       undefined method `each' for nil:NilClass

Factories:

//schedules.rb
FactoryGirl.define do
  factory :schedule do
    date        {Time.now + (1..10).to_a.sample.hours}
    message     {Faker::ChuckNorris.fact}
    user
  end
end


//workers.rb
FactoryGirl.define do
  factory :worker do
    name    "Iggy Worker"
    phone   "1112223333"
    schedule
  end
end

I don't quite understand the error, undefined method each' for nil:NilClass, what is the class it is referring to? How can I change my RSpec to mimic the POST request sent by react and create a passing POST test?

Aucun commentaire:

Enregistrer un commentaire