Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update RSpec/IteratedExpectation cop documentation with an example of a matcher relying on block arguments #1659

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions docs/modules/ROOT/pages/cops_rspec.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -2710,6 +2710,26 @@ end
it 'validates users' do
expect([user1, user2, user3]).to all(be_valid)
end

# bad
it 'sets inferred fields for users' do
[user1, user2, user3].each do |user|
expect(user).to have_attributes(
post_count: PostService.new(user).post_count,
karma: KarmaService.new(user).value
)
end
end

# good
it 'sets inferred fields for users' do
expect([user1, user2, user3]).to all(satisfy do |user|
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would the following work?
‘’’
expect([user1, user2, user3]).to all have_attributes(
‘’’

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would certainly be more readable, but unfortunately not in this scenario (where block arguments are used). The challenge is that the have_attributes call is receiving the user as an argument. It would raise "undefined local variable or method `user'"

have_attributes(
post_count: PostService.new(user).post_count,
karma: KarmaService.new(user).value
)
end)
end
----

=== References
Expand Down
20 changes: 20 additions & 0 deletions lib/rubocop/cop/rspec/iterated_expectation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,26 @@ module RSpec
# expect([user1, user2, user3]).to all(be_valid)
# end
#
# # bad
# it 'sets inferred fields for users' do
# [user1, user2, user3].each do |user|
# expect(user).to have_attributes(
# post_count: PostService.new(user).post_count,
# karma: KarmaService.new(user).value
# )
# end
# end
#
# # good
# it 'sets inferred fields for users' do
# expect([user1, user2, user3]).to all(satisfy do |user|
# have_attributes(
# post_count: PostService.new(user).post_count,
# karma: KarmaService.new(user).value
# )
# end)
# end
#
class IteratedExpectation < Base
MSG = 'Prefer using the `all` matcher instead ' \
'of iterating over an array.'
Expand Down