Skip to content

Commit

Permalink
Fail Include matcher when comparing String with non-String
Browse files Browse the repository at this point in the history
If the actual is a String and the expected is not, a `TypeError` occurs
when we try to call `actual.include?`, becuase this method expects
a String when called on a String.

If the actual is a `String` and the expected is not, then the match
can't possibly succeed and we can return early.
  • Loading branch information
naveg committed Feb 2, 2024
1 parent 96a3e5a commit 06ba2d2
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/rspec/matchers/built_in/include.rb
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,9 @@ def actual_hash_has_key?(expected_key)
end

def actual_collection_includes?(expected_item)
# if the actual is a String, the expected_item must also be a String
return false if actual.is_a?(String) && !expected_item.is_a?(String)

return true if actual.include?(expected_item)

# String lacks an `any?` method...
Expand Down
10 changes: 10 additions & 0 deletions spec/rspec/matchers/built_in/include_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,10 @@ def hash.send; :sent; end
expect("abc").to include("a")
end

it "passes if target includes multiple expecteds" do
expect(" foo\nbar\nbazz").to include("foo", "bar", "baz")
end

it "fails if target does not include expected" do
expect {
expect("abc").to include("d")
Expand All @@ -227,6 +231,12 @@ def hash.send; :sent; end
}.to fail_with(a_string_not_matching(/Diff/i))
end

it "fails when matching a collection" do
expect {
expect("foo").to include({:bar => "baz"})
}.to fail_with(/expected "foo" to include {:bar => "baz"}/)
end

context "with exact count" do
it 'fails if the block yields wrong number of times' do
expect {
Expand Down

0 comments on commit 06ba2d2

Please sign in to comment.