A user
has many comments
, so I would like to have a factory user
with a comment
associated to it (user_with_comment
):
factory :user, class: User do |t|
...
factory :user_with_comment do |t|
after(:create) do |user|
FactoryGirl.create(:comment, user_id: user.id)
end
end
It works fine... when I call FactoryGirl.create(:user_with_comment)
, it creates the user
and the related comment
in my test db
.
However, I'm facing some issues in the controller_spec
:
Using let
I have to reload the user
to see the comment
:
let(:user) { FactoryGirl.create(:user_with_comment) }
user.comments.size #=>0
user.reload
user.comments.size #=>1
One solution would be using before(:each)
, but it will create venda
and comment
before each test:
before(:each) do
@user = FactoryGirl.create(:user_with_comment)
end
@user.comments.size #=>1
Or, I can reload the user
before each test, but it will also hit the database:
let(:user) { FactoryGirl.create(:user_with_comment) }
before(:each) do
user.reload
end
What is the best approach in this situation?
let
is perfect. I think so. – Hobbism