I have a problem with testing my Controllers. All tests are working fine, the Controllers are basic CRUD, but one #index action always returns an empty JSON body. I've tried everything and ran out of ideas, so maybe you can help me.
Here is my Code
Controller
class CarUsersController < ApplicationController
def index
@car_users = CarUser.all
render json: @car_users
end
Migration
class CreateCarUsers < ActiveRecord::Migration[5.0]
def change
create_table :car_users do |t|
t.integer :car_id
t.integer :owner_user_id
t.integer :rental_user_id
t.integer :service_user_id
t.string :role
t.timestamps
end
end
end
Model
class CarUser < ApplicationRecord
rolify
belongs_to :car
belongs_to :owner_user
belongs_to :rental_user
belongs_to :service_user
validates :role, presence: true
validates :role, acceptance: { accept: ['owner', 'rental', 'service'] }
end
RSpec Factory
require 'faker'
FactoryGirl.define do
factory :car_user do |p|
p.owner_user_id { Faker::Number.digit }
p.driver_user_id { Faker::Number.digit }
p.service_user_id { Faker::Number.digit }
p.car_id { Faker::Number.digit }
p.role 'owner'
end
end
And the RSpec-Test
...
it 'returns all car users' do
FactoryGirl.create(:car_user, rental_user_id: 4, car_id: 2, role: 'rental')
get :index
puts response.body
parsed_response = JSON.parse(response.body)
expect(parsed_response[0]['id']).to eq(1)
expect(parsed_response[0]['rental_user_id']).to eq(4)
expect(parsed_response[0]['car_id']).to eq(2)
expect(parsed_response[0]['role']).to eq('rental')
end
...
I always get the following error:
CarUsersController returns all car users
Failure/Error: expect(parsed_response[0]['rental_user_id'].to eq(4)
expected: 4
got: nil
(compared using ==)
Aucun commentaire:
Enregistrer un commentaire