ruby on rails - association.first returns nil in an RSpec feature spec using a FactoryGirl factory with a has_many association -
i have following in rails 4 app:
factorygirl.define factory :todo_list after(:create) |t| create_list(:item, 3, todo_list: t) end factory :public_todo_list is_public true end end factory :item sequence(:position) { |n| n } name "this item ##{:position}?" todo_list end end i have following in feature spec:
feature "todolists" let(:todo_list) { create(:public_todo_list) } scenario "something requires accessing first item" ... pending todo_list.items.first.name ... end end however, test fails following:
failure/error: pending todo_list.items.first.name nomethoderror: undefined method `name' nil:nilclass being todo_list.items activerecord::associations::collectionproxy::activerecord_associations_collectionproxy_item object, seems first should return first item record? nil instead. todo_list.items.count returns 3 , test.log shows records being created correctly. missing?
try reloading association before accessing first item:
todo_list.items.reload i think reload needed because todo_list object doesn't have item when created, , suspect rspec caches this. items created after creation of todo_list object.
Comments
Post a Comment