2017-04-11 69 views
0

我在測試我的控制器時遇到了問題。所有測試工作正常,控制器是基本的CRUD,但是一個#index動作總是返回一個空的JSON體。我已經嘗試過所有的想法,所以也許你可以幫助我。Rails API服務器RSpec測試總是返回空JSON

這裏是我的代碼

控制器

class CarUsersController < ApplicationController 

def index 
    @car_users = CarUser.all 

    render json: @car_users 
end 

遷移

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 

型號

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的工廠

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 

而RSpec的試驗

... 
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 
... 

我總是得到以下錯誤:

CarUsersController returns all car users 
Failure/Error: expect(parsed_response[0]['rental_user_id'].to eq(4) 

    expected: 4 
     got: nil 

    (compared using ==) 
+0

從'puts response.body'行輸出什麼? **編輯**:您的工廠不接受'rental_user'關聯,可能就是這樣。你也應該儘量避免硬編碼(特別是對於模型ID)。存儲您從工廠獲得的car_user對象並與之進行比較。 – MrDanA

+0

just [{「id」:1}] – mfaorlkzus

+0

你使用序列化程序嗎? – radubogdan

回答

0

ŧ他在這裏的問題是,您沒有將rental_association添加到您的工廠。

另外,您應該避免在您的期望範圍內進行硬編碼。相反,您可以保存car_user實例並與之進行比較。特別是隨着標識

car_user = FactoryGirl.create(role: "rental", ...) 
... 
expect(parsed_response[0]['id']).to eq(car_user.id) 
expect(parsed_response[0]['role']).to eq(car_user.role) 

,他們將永遠不會永遠是1,如果你的測試是在一個不同的順序運行,而另一個CarUser首先提出,這將現在總是失敗。此外,如果您曾經更改過發送給工廠的單個值,則必須隨後手動將其更改。例如,在這種情況下,如果您將角色更改爲「所有者」,則您現在不必更改預期行。