0
テストがあります。そのインデックスアクションは、すべての質問の配列を取り込みます。rspec test 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は、すべてのアレイを移入します質問 失敗/エラー:expect(assigns(:questions))。to 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)>'
なぜ同じコレクションの要素がありますか?
あなたはこのコードを何、説明することができます:@questions = [FactoryGirl.build_stubbed(:質問)](すべて)FactoryGirl.build_stubbed' '、.and_return(@questions) –
確認 は、(質問)を受信できるよう.TOデータベースに書き込まずにActiveRecordオブジェクト(すべてのプロパティを持つ)を作成します。 'allow(...)。to receive'コールは、データベースへの呼び出しを(この場合)呼び出すために使われます。つまり、' Question.all'が呼び出されたときに '@ questions'を返します。ここでモデルをテストしているわけではないので、dbコールを模擬することができます。実際には、スタック全体を実行する統合テストをコード化する場合、コントローラテストは一切必要ありません。 –
ありがとうございます。良い –