2016-10-31 38 views
0

我測試。,該索引操作'填充所有問題的數組。rspec測試GET #index - 包含的預期集合

require 'rails_helper' 

RSpec.describe QuestionsController, type: :controller do 
    describe 'GET #index' do 
    before do 
     @questions = FactoryGirl.create_list(:question, 2) 
     get :index 
    end 

    it 'populates an array of all questions' do 
     binding.pry 
     expect(assigns(:questions)).to match_array(@questions) 
    end 
    it 'renders index view' do 
     expect(response).to render_template(:index) 
    end 
    end 
end 

控制器/ questions_controller

class QuestionsController < ApplicationController 
    def index 
     @questions = Question.all   
    end 
end 

工廠/ questions.rb

FactoryGirl.define do 
    factory :question do 
    title "MyString" 
    body "MyText" 
    end 
end 

當運行測試顯示錯誤:

1)QuestionsController GET #INDEX填充所有的陣列問題 失敗/錯誤:期待(分配(:問題))。 match_array(@questions)

expected collection contained: 

[#<Question id: 37, title: "MyString", body: "MyText", created_at: "2016-10-31 19:37:12", updated_at:...: "MyString", body: "MyText", created_at: "2016-10-31 19:37:12", updated_at: "2016-10-31 19:37:12">] 
     actual collection contained: [#<Question id: 15, title: "MyString", body: "MyText", created_at: "2016-10-30 21:23:52", updated_at:...: "MyString", body: "MyText", created_at: "2016-10-31 19:37:12", updated_at: "2016-10-31 19:37:12">] 
     the extra elements were:  [#<Question id: 15, title: "MyString", body: "MyText", created_at: "2016-10-30 21:23:52", updated_at:...: "MyString", body: "MyText", created_at: "2016-10-30 21:23:52", updated_at: "2016-10-30 21:23:52">] 
# ./spec/controllers/questions_controller_spec.rb:12:in `block (3 levels) in <top (required)>' 

爲什麼不是集合中的相同元素?

回答

1

你需要在db中創建問題嗎?如果你正在測試一個@questions是越來越稀少,您可以存根的電話分貝,像

describe 'GET #index' do 
    before do 
    @questions = [FactoryGirl.build_stubbed(:question)] 
    allow(Question).to receive(:all).and_return(@questions) 
    get :index 
    end 

    it 'populates an array of all questions' do 
    expect(assigns(:questions)).to match_array(@questions) 
    end 
end 

,如果你只是想測試分配你並不需要創建實際的數據庫記錄。

+0

你能解釋一下,什麼做到這一點代碼:@questions = [FactoryGirl.build_stubbed(:問題) 允許(問題)。爲了接收(:所有).and_return(@questions) –

+0

肯定的是,'FactoryGirl.build_stubbed'將創建一個ActiveRecord對象(及其所有屬性)而不寫入數據庫。 'allow(...)。'接收'調用被用來模擬(在這種情況下)對數據庫的調用,所以,這就是說:好吧,當'Question.all'獲得調用時,返回'@ questions'。 ..因爲你沒有在這裏測試模型,所以你可以模擬數據庫調用,事實上,如果你編寫一個集成測試來執行整個堆棧 –

+0

謝謝,你根本不需要控制器測試。好的 –