8000 Merge pull request #183 from jrmhaig/array_match_diff · rspec/rspec@43c7560 · GitHub
[go: up one dir, main page]

Skip to content

Commit 43c7560

Browse files
authored
Merge pull request #183 from jrmhaig/array_match_diff
[rspec-expectations] Fix message when matching array with non-array
2 parents 4cf3656 + 812abff commit 43c7560

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

rspec-expectations/lib/rspec/matchers/built_in/match.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@ def with_captures(*captures)
3535
self
3636
end
3737

38+
# @api private
39+
# @return [String]
40+
def failure_message
41+
if Array === expected && !(actual.respond_to?(:to_a) || actual.respond_to?(:to_ary))
42+
return "expected a collection that can be converted to an array with " \
43+
"`#to_ary` or `#to_a`, but got #{actual_formatted}"
44+
end
45+
46+
super
47+
end
48+
3849
private
3950

4051
def match(expected, actual)
@@ -46,6 +57,7 @@ def match(expected, actual)
4657

4758
def can_safely_call_match?(expected, actual)
4859
return false unless actual.respond_to?(:match)
60+
return false if Array === expected
4961

5062
!(RSpec::Matchers.is_a_matcher?(expected) &&
5163
(String === actual || Regexp === actual))

rspec-expectations/spec/rspec/matchers/built_in/match_spec.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,12 @@
9595
expect(description).to eq("match [(a string matching /foo/), (a value within 0.2 of 1)]")
9696
end
9797
end
98+
99+
it "fails when target type (String) does not match expected (Array)" do
100+
expect {
101+
expect("string").to match(["c", "a", "b"])
102+
}.to fail_with('expected a collection that can be converted to an array with `#to_ary` or `#to_a`, but got "string"')
103+
end
98104
end
99105

100106
RSpec.describe "expect(...).not_to match(expected)" do
@@ -135,4 +141,8 @@
135141
}.to fail_with('expected ["fod", 1.1] not to match [(a string matching /fod/), (a value within 0.2 of 1)]')
136142
end
137143
end
144+
145+
it "passes when target type (String) does not match expected (Array)" do
146+
expect("string").not_to match(["c", "a", "b"])
147+
end
138148
end

0 commit comments

Comments
 (0)
0