###前提・実現したいこと
RSpecのコントローラーのテストで、レコードが作成されているかテストをしています。
「親レコードが作成されているか」のテストはうまくいくのですが、「子レコードの作成ができているか」のテストがうまくいきません。
ちなみに、テスト対象の動きは実際に親レコード、子レコード共に作成されています。
どなたか子レコード作成のテストに関することをご教授ください!
###発生している問題・エラーメッセージ
Failure/Error: expect { post :create, event: attributes_for(:event_create) }.to change(User, :count).by(1) expected #count to have changed by 1, but was changed by 0
###該当のソースコード
コントローラーのテストコードはこちら↓
Ruby
1#/spec/controller/events_controller_spec.rb 2 3#====親レコードはパスする===== 4describe "Modelに正常な値をセット" do 5 it "EventsTableにレコードが1つ作成されること" do 6 expect { 7 post :create, event: attributes_for(:event) 8 }.to change(Event, :count).by(1) 9 end 10#====子レコードは作成できてないとエラーが出る==== 11 it "UserTableにレコードが1つ作成されること" do 12 expect { 13 post :create, event: attributes_for(:event_create) 14 }.to change(User, :count).by(1) 15 end
ファクトリの定義はこちら↓
Ruby
1#/spec/factories/events.rb 2FactoryGirl.define do 3 factory :event_create, class: Event do 4 title "title" 5 author_attributes { attributes_for(:user) } 6 end 7end 8 9#/spec/factories/users.rb 10FactoryGirl.define do 11 factory :user, class: User do 12 name "name" 13 end 14end
テスト対象のコントローラー↓
Ruby
1#/controllers/events_controller #create 2 def create 3 @event = Event.new(event_params) 4 if @event.save 5 redirect_to event_path(@event.id) 6 else 7 render new_event_path 8 end 9 end
テスト対象のモデル↓
Ruby
1#/models/event.rb 2class Event < ActiveRecord::Base 3 has_many :users 4 validates :title, presence: true 5 6#/models/user.rb 7class User < ActiveRecord::Base 8 belongs_to :event 9 validates :name, presence: true 10end
###補足情報(言語/FW/ツール等のバージョンなど)
RSpec -v "3.5.2"
FactoryGirl
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。