While I was studying, I found something I didn't understand.
Why should I review the instance variable
When I read the article above, it said this.
Let is called at the required time, but before instance variable definition is called at all times.Therefore, it will be created even when you don't need it in context.
In the case of RSpec, it is recommended to avoid instance variables from this perspective, as record generation and DB access often affect execution time.
Then, on the contrary, I don't understand what happens when I have to use let!
.
Is there any problem if I evaluate the delay?
I'm a beginner, so I'd appreciate it if you could teach me something easy.
Thank you for your cooperation.
class Article <ApplicationRecord
has_many —Comments
end
class Comment <ApplicationRecord
belongs_to —article
end
When there is a model like the one above,
let(:article) {create(:article)}
let(:article_comments) {create_list(:comment,3,article_id:article.id)}
it'has3 comments'do
num_comments=article.comments.count
expect(num_comments).to eqarticle_comments.count
end
I think this will be an error.This is because article_comments
was not called when calculating the first num_comments
, resulting in num_comments
being 0
.
In the example above, if you specify article_comments
let!
, it will work as intended.
© 2024 OneMinuteCode. All rights reserved.