testsurfer 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,217 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Testsurfer
4
+ # Events, waits, routes and bindings shared by pages and contexts.
5
+ # The events come from the context's stream; a page in a context
6
+ # opened without interception has none, and these calls say so.
7
+ module EventTarget
8
+ # Run the block for every `event` (`"console"`, `"request"`,
9
+ # `"popup"`, ...) with its value. A `"dialog"` handler answers the
10
+ # dialog (accept or dismiss it there); with none, dialogs are
11
+ # dismissed, as in Playwright. Returns an id for `off`.
12
+ def on(event, callable = nil, &blk)
13
+ f = callable || blk
14
+ raise UsageError, "on(#{event.inspect}) needs a block" if f.nil?
15
+
16
+ if event.to_s == "dialog"
17
+ events.sync { events.dialogs << [f, false] }
18
+ return f
19
+ end
20
+ events.add_listener(event.to_s, false, f)
21
+ end
22
+
23
+ # `on`, for the next event only.
24
+ def once(event, callable = nil, &blk)
25
+ f = callable || blk
26
+ raise UsageError, "once(#{event.inspect}) needs a block" if f.nil?
27
+
28
+ if event.to_s == "dialog"
29
+ events.sync { events.dialogs << [f, true] }
30
+ return f
31
+ end
32
+ events.add_listener(event.to_s, true, f)
33
+ end
34
+
35
+ # Remove a listener: by the id `on` returned, or by event and block.
36
+ def off(event_or_id, callable = nil)
37
+ if event_or_id.to_s == "dialog"
38
+ events.sync { events.dialogs.reject! { |f, _| callable.nil? || f == callable } }
39
+ else
40
+ events.remove_listener(event_or_id, callable)
41
+ end
42
+ nil
43
+ end
44
+ alias remove_listener off
45
+
46
+ # The next `event` the predicate accepts. With a block, the block
47
+ # runs after the wait is in place (the action that causes the event),
48
+ # so the event cannot slip by. Returns the event's value.
49
+ def expect_event(event, predicate: nil, timeout: nil, &action)
50
+ name = event.to_s
51
+ slot = events.waiter { |e| e.name == name && (predicate.nil? || predicate.call(e.value)) }
52
+ action&.call
53
+ Events.wait(slot, timeout || event_timeout, "#{wait_api_name}.waitForEvent").value
54
+ end
55
+ alias wait_for_event expect_event
56
+
57
+ # Routes: answer every request whose URL matches (a `**` glob, an
58
+ # exact URL, or a pattern) with the block, which gets the Route and
59
+ # the Request. Later routes go first. `times:` limits the matches.
60
+ def route(url, handler = nil, times: nil, &blk)
61
+ need_events!("#{wait_api_name}.route")
62
+ h = handler || blk
63
+ raise UsageError, "route needs a handler" if h.nil?
64
+
65
+ matcher = UrlMatcher.new(url) { |s| Testsurfer.resolve_against(base_url, s) }
66
+ events.sync { events.routes << [matcher, h, times, EventState.next_id] }
67
+ sync_routing
68
+ end
69
+
70
+ # Remove the routes for `url` (all of them without a handler, or the one with it).
71
+ def unroute(url, handler = nil)
72
+ events.sync do
73
+ events.routes.reject! { |m, h, _, _| m.source == url && (handler.nil? || h == handler) }
74
+ end
75
+ sync_routing
76
+ end
77
+
78
+ # Remove every route.
79
+ def unroute_all(**)
80
+ events.sync { events.routes.clear }
81
+ sync_routing
82
+ end
83
+ end
84
+
85
+ class Page
86
+ include EventTarget
87
+
88
+ def wait_api_name
89
+ "page"
90
+ end
91
+
92
+ def need_events!(what)
93
+ return if context.events?
94
+
95
+ raise UsageError, "#{what} needs an intercepting context (the default context options)"
96
+ end
97
+
98
+ def sync_routing
99
+ context.hub.sync_routing(wire, session_id)
100
+ nil
101
+ end
102
+
103
+ def event_timeout
104
+ timeouts.action
105
+ end
106
+
107
+ # Make `name(...args)` in the page call the block here and resolve
108
+ # with its result, as Playwright's `exposeFunction`. Survives navigations.
109
+ def expose_function(name, callable = nil, &blk)
110
+ need_events!("page.exposeFunction")
111
+ f = callable || blk
112
+ events.sync do
113
+ raise UsageError, "Function \"#{name}\" has been already registered" if events.bindings.key?(name.to_s)
114
+
115
+ events.bindings[name.to_s] = f
116
+ end
117
+ script = Events.binding_script(name.to_s)
118
+ add_init_script(script)
119
+ if page_id
120
+ begin
121
+ evaluate("(#{script}, 0)")
122
+ rescue Error
123
+ nil
124
+ end
125
+ end
126
+ nil
127
+ end
128
+
129
+ # The next popup this page opens.
130
+ def expect_popup(predicate: nil, timeout: nil, &blk)
131
+ expect_event("popup", predicate: predicate, timeout: timeout, &blk)
132
+ end
133
+ alias wait_for_popup expect_popup
134
+
135
+ def expect_download(predicate: nil, timeout: nil, &blk)
136
+ expect_event("download", predicate: predicate, timeout: timeout, &blk)
137
+ end
138
+ alias wait_for_download expect_download
139
+
140
+ def expect_console_message(predicate: nil, timeout: nil, &blk)
141
+ expect_event("console", predicate: predicate, timeout: timeout, &blk)
142
+ end
143
+ alias wait_for_console_message expect_console_message
144
+
145
+ def expect_file_chooser(predicate: nil, timeout: nil, &blk)
146
+ expect_event("filechooser", predicate: predicate, timeout: timeout, &blk)
147
+ end
148
+ alias wait_for_file_chooser expect_file_chooser
149
+
150
+ def expect_websocket(predicate: nil, timeout: nil, &blk)
151
+ expect_event("websocket", predicate: predicate, timeout: timeout, &blk)
152
+ end
153
+ alias wait_for_web_socket expect_websocket
154
+ alias wait_for_websocket expect_websocket
155
+
156
+ def expect_worker(predicate: nil, timeout: nil, &blk)
157
+ expect_event("worker", predicate: predicate, timeout: timeout, &blk)
158
+ end
159
+ alias wait_for_worker expect_worker
160
+
161
+ # The next request whose URL matches (a glob, URL or pattern; or a block test).
162
+ def expect_request(url_or_predicate, timeout: nil, &blk)
163
+ test = url_test(url_or_predicate)
164
+ expect_event("request", predicate: ->(r) { test.call(r) }, timeout: timeout, &blk)
165
+ end
166
+ alias wait_for_request expect_request
167
+
168
+ # The next response whose URL matches.
169
+ def expect_response(url_or_predicate, timeout: nil, &blk)
170
+ test = url_test(url_or_predicate)
171
+ expect_event("response", predicate: ->(r) { test.call(r) }, timeout: timeout, &blk)
172
+ end
173
+ alias wait_for_response expect_response
174
+
175
+ # Returns once the page closes (the block runs first).
176
+ def wait_for_close(timeout: nil, &blk)
177
+ expect_event("close", timeout: timeout, &blk)
178
+ nil
179
+ end
180
+
181
+ # Up to 200 recent console messages.
182
+ def console_messages
183
+ events.sync { events.console.dup }
184
+ end
185
+
186
+ # Up to 200 recent uncaught errors.
187
+ def page_errors
188
+ events.sync { events.errors.dup }
189
+ end
190
+
191
+ # Up to 100 recent requests.
192
+ def requests
193
+ events.sync { events.requests.dup }
194
+ end
195
+
196
+ # Answer the page's WebSockets whose URL matches with the block
197
+ # (it gets a WebSocketRoute) instead of the server. Later routes go first.
198
+ def route_web_socket(url, handler = nil, &blk)
199
+ h = handler || blk
200
+ matcher = UrlMatcher.new(url) { |s| resolve_url(s).sub("http", "ws") }
201
+ hooks_sync { hook_state[:routes].unshift([matcher, h]) }
202
+ on = "window.__ts && (window.__ts.wsRouting = true);"
203
+ add_init_script(on)
204
+ evaluate("() => { #{on} return null; }") if page_id
205
+ nil
206
+ end
207
+
208
+ private
209
+
210
+ def url_test(m)
211
+ return m if m.respond_to?(:call)
212
+
213
+ matcher = UrlMatcher.new(m) { |s| resolve_url(s) }
214
+ ->(r) { matcher.match?(r.url) }
215
+ end
216
+ end
217
+ end
@@ -0,0 +1,342 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Testsurfer
6
+ # A JavaScript regular expression: source and flags as the page reads
7
+ # them. Pass one where a pattern must use JavaScript syntax; a Ruby
8
+ # Regexp works too (its `i` and `m` flags become `i` and `s`).
9
+ JSRegex = Struct.new(:source, :flags) do
10
+ def initialize(source, flags = "")
11
+ super(source.to_s, flags.to_s)
12
+ end
13
+
14
+ def to_s
15
+ "/#{source}/#{flags}"
16
+ end
17
+ end
18
+
19
+ # A JavaScript regular expression, for any argument that takes a
20
+ # string or a pattern: `Testsurfer.re("^Sign (in|up)$", "i")`.
21
+ def self.re(source, flags = "")
22
+ JSRegex.new(source, flags)
23
+ end
24
+
25
+ # Text to match: a string, or a pattern (Regexp or JSRegex).
26
+ module TextMatch
27
+ module_function
28
+
29
+ def js_flags(re)
30
+ f = +""
31
+ f << "i" if re.options.anybits?(Regexp::IGNORECASE)
32
+ f << "s" if re.options.anybits?(Regexp::MULTILINE)
33
+ f
34
+ end
35
+
36
+ def regex?(t)
37
+ t.is_a?(Regexp) || t.is_a?(JSRegex)
38
+ end
39
+
40
+ # [source, flags] of a pattern.
41
+ def parts(t)
42
+ t.is_a?(Regexp) ? [t.source, js_flags(t)] : [t.source, t.flags]
43
+ end
44
+
45
+ def check!(t)
46
+ return t if t.is_a?(String) || regex?(t)
47
+ return t.to_s if t.is_a?(Symbol) || t.is_a?(Numeric)
48
+
49
+ raise UsageError, "expected a String or a Regexp, got #{t.inspect}"
50
+ end
51
+
52
+ # As a literal in Playwright's notation: `'text'` or `/source/flags`.
53
+ def literal(t)
54
+ return Query.quote(t) unless regex?(t)
55
+
56
+ s, f = parts(t)
57
+ "/#{s}/#{f}"
58
+ end
59
+
60
+ # The engine's matcher form; `exact` applies to strings only.
61
+ def wire(t, exact)
62
+ return { "s" => t, "exact" => exact } unless regex?(t)
63
+
64
+ { "re" => parts(t) }
65
+ end
66
+
67
+ # The assertion engine's form (no `exact`).
68
+ def wire_plain(t)
69
+ return { "s" => t } unless regex?(t)
70
+
71
+ { "re" => parts(t) }
72
+ end
73
+
74
+ # How Playwright shows an expected value: JSON for strings, `/re/` for patterns.
75
+ def show(t)
76
+ regex?(t) ? literal(t) : JSON.generate(t)
77
+ end
78
+
79
+ # A Ruby Regexp for testing locally (URL matchers).
80
+ def to_regexp(t)
81
+ return t if t.is_a?(Regexp)
82
+
83
+ opts = 0
84
+ opts |= Regexp::IGNORECASE if t.flags.include?("i")
85
+ opts |= Regexp::MULTILINE if t.flags.include?("s")
86
+ Regexp.new(t.source, opts)
87
+ end
88
+ end
89
+
90
+ # Options of `get_by_role`, as Playwright's `getByRole` takes them.
91
+ class ByRole
92
+ KEYS = %i[name exact checked disabled expanded include_hidden level pressed selected].freeze
93
+ attr_accessor(*KEYS)
94
+ # role= selector `[name="x"]`: whole string, case-insensitive.
95
+ attr_accessor :name_full
96
+
97
+ def initialize(**opts)
98
+ opts.each do |k, v|
99
+ raise UsageError, "get_by_role: unknown option #{k}" unless KEYS.include?(k)
100
+
101
+ send("#{k}=", v)
102
+ end
103
+ @name = TextMatch.check!(@name) unless @name.nil?
104
+ @name_full = false
105
+ end
106
+
107
+ def self.tri_text(v)
108
+ v == "mixed" || v == :mixed ? "'mixed'" : v.to_s
109
+ end
110
+
111
+ def self.tri_json(v)
112
+ v == "mixed" || v == :mixed ? "mixed" : v
113
+ end
114
+
115
+ # `, { name: 'x', exact: true }` as Playwright prints the options.
116
+ def describe
117
+ parts = []
118
+ parts << "name: #{TextMatch.literal(name)}" unless name.nil?
119
+ parts << "exact: #{exact}" unless exact.nil?
120
+ parts << "checked: #{ByRole.tri_text(checked)}" unless checked.nil?
121
+ parts << "disabled: #{disabled}" unless disabled.nil?
122
+ parts << "expanded: #{expanded}" unless expanded.nil?
123
+ parts << "includeHidden: #{include_hidden}" unless include_hidden.nil?
124
+ parts << "level: #{level}" unless level.nil?
125
+ parts << "pressed: #{ByRole.tri_text(pressed)}" unless pressed.nil?
126
+ parts << "selected: #{selected}" unless selected.nil?
127
+ parts.empty? ? "" : ", { #{parts.join(', ')} }"
128
+ end
129
+
130
+ def wire
131
+ o = {}
132
+ o["checked"] = ByRole.tri_json(checked) unless checked.nil?
133
+ o["disabled"] = disabled unless disabled.nil?
134
+ o["expanded"] = expanded unless expanded.nil?
135
+ o["includeHidden"] = include_hidden unless include_hidden.nil?
136
+ o["level"] = level unless level.nil?
137
+ o["pressed"] = ByRole.tri_json(pressed) unless pressed.nil?
138
+ o["selected"] = selected unless selected.nil?
139
+ unless name.nil?
140
+ o["name"] = if name.is_a?(String) && name_full
141
+ { "s" => name, "full" => true }
142
+ else
143
+ TextMatch.wire(name, exact || false)
144
+ end
145
+ end
146
+ o
147
+ end
148
+ end
149
+
150
+ # Filters on a locator's matches: Playwright's `filter()` options.
151
+ # `has` and `has_not` hold chains (from locators).
152
+ class Filter
153
+ attr_accessor :has_text, :has_not_text, :has, :has_not, :visible
154
+
155
+ def initialize(has_text: nil, has_not_text: nil, has: nil, has_not: nil, visible: nil)
156
+ @has_text = has_text.nil? ? nil : TextMatch.check!(has_text)
157
+ @has_not_text = has_not_text.nil? ? nil : TextMatch.check!(has_not_text)
158
+ @has = has.respond_to?(:chain) ? has.chain : has
159
+ @has_not = has_not.respond_to?(:chain) ? has_not.chain : has_not
160
+ @visible = visible
161
+ end
162
+
163
+ def describe
164
+ parts = []
165
+ parts << "hasText: #{TextMatch.literal(has_text)}" unless has_text.nil?
166
+ parts << "hasNotText: #{TextMatch.literal(has_not_text)}" unless has_not_text.nil?
167
+ parts << "has: #{has.describe}" unless has.nil?
168
+ parts << "hasNot: #{has_not.describe}" unless has_not.nil?
169
+ parts << "visible: #{visible}" unless visible.nil?
170
+ "filter({ #{parts.join(', ')} })"
171
+ end
172
+
173
+ def wire
174
+ o = {}
175
+ o["hasText"] = TextMatch.wire(has_text, false) unless has_text.nil?
176
+ o["hasNotText"] = TextMatch.wire(has_not_text, false) unless has_not_text.nil?
177
+ o["has"] = has.wire unless has.nil?
178
+ o["hasNot"] = has_not.wire unless has_not.nil?
179
+ o["visible"] = visible unless visible.nil?
180
+ o
181
+ end
182
+ end
183
+
184
+ # One kind of query a step runs. `kind` is one of :role, :text,
185
+ # :label, :css, :xpath, :attr, :and, :or, :frame, :self, :handle, :invalid.
186
+ class Query
187
+ attr_reader :kind, :o
188
+
189
+ def initialize(kind, **o)
190
+ @kind = kind
191
+ @o = o
192
+ end
193
+
194
+ def [](k)
195
+ @o[k]
196
+ end
197
+
198
+ # A string in Playwright's locator notation: single quotes, escaped.
199
+ def self.quote(s)
200
+ "'#{s.to_s.gsub("\\") { "\\\\" }.gsub("'") { "\\'" }}'"
201
+ end
202
+
203
+ def describe
204
+ case kind
205
+ when :role then "getByRole(#{Query.quote(o[:role])}#{o[:options].describe})"
206
+ when :text then "getByText(#{TextMatch.literal(o[:text])}#{o[:exact] ? ', { exact: true }' : ''})"
207
+ when :label then "getByLabel(#{TextMatch.literal(o[:text])}#{o[:exact] ? ', { exact: true }' : ''})"
208
+ when :css then "locator(#{Query.quote(o[:selector])})"
209
+ when :xpath then "locator(#{Query.quote("xpath=#{o[:xpath]}")})"
210
+ when :attr
211
+ if o[:method] == "locator"
212
+ v = TextMatch.regex?(o[:value]) ? TextMatch.literal(o[:value]) : o[:value]
213
+ "locator(#{Query.quote("#{o[:attr]}=#{v}")})"
214
+ else
215
+ ex = o[:exact] && o[:method] != "getByTestId" ? ", { exact: true }" : ""
216
+ "#{o[:method]}(#{TextMatch.literal(o[:value])}#{ex})"
217
+ end
218
+ when :and then "#{o[:l].describe}.and(#{o[:r].describe})"
219
+ when :or then "#{o[:l].describe}.or(#{o[:r].describe})"
220
+ when :frame then "contentFrame()"
221
+ when :self then ""
222
+ when :invalid then o[:selector]
223
+ when :handle then "ElementHandle"
224
+ end
225
+ end
226
+
227
+ # The engine's wire form; an unparsable selector raises its message.
228
+ def wire
229
+ case kind
230
+ when :role then { "k" => "role", "role" => o[:role], "o" => o[:options].wire }
231
+ when :text
232
+ { "k" => "text", "t" => TextMatch.wire(o[:text], o[:exact]), "light" => o[:light] || false, "legacy" => o[:legacy] || false }
233
+ when :label then { "k" => "label", "t" => TextMatch.wire(o[:text], o[:exact]) }
234
+ when :css then { "k" => "css", "sel" => o[:selector], "light" => o[:light] || false }
235
+ when :xpath then { "k" => "xpath", "xp" => o[:xpath] }
236
+ when :attr
237
+ { "k" => "attr", "a" => o[:attr], "t" => TextMatch.wire(o[:value], o[:exact]),
238
+ "testid" => o[:method] == "getByTestId" || o[:method] == "locator" }
239
+ when :and then { "k" => "and", "l" => o[:l].wire_checked, "r" => o[:r].wire_checked }
240
+ when :or then { "k" => "or", "l" => o[:l].wire_checked, "r" => o[:r].wire_checked }
241
+ when :frame then { "k" => "frame" }
242
+ when :self then { "k" => "self" }
243
+ when :handle then { "k" => "handle", "id" => o[:id] }
244
+ when :invalid then raise InvalidSelector, "Error: #{o[:message]}"
245
+ end
246
+ end
247
+
248
+ # Raised by `wire` for a selector that did not parse.
249
+ class InvalidSelector < StandardError; end
250
+ end
251
+
252
+ # One link of a chain: a query, its filters, and an optional index.
253
+ class Step
254
+ attr_accessor :query, :filters, :index, :capture
255
+
256
+ def initialize(query, filters: [], index: nil, capture: false)
257
+ @query = query
258
+ @filters = filters
259
+ @index = index
260
+ @capture = capture
261
+ end
262
+
263
+ def dup_step
264
+ Step.new(query, filters: filters.dup, index: index, capture: capture)
265
+ end
266
+ end
267
+
268
+ # A locator's chain of steps.
269
+ class Chain
270
+ attr_reader :steps
271
+
272
+ def initialize(steps = [])
273
+ @steps = steps
274
+ end
275
+
276
+ def self.of(query)
277
+ new([Step.new(query)])
278
+ end
279
+
280
+ # The chain in Playwright's notation, as messages print it:
281
+ # `getByRole('button', { name: 'Go' }).first()`.
282
+ def describe
283
+ out = +""
284
+ steps.each do |s|
285
+ part = +s.query.describe
286
+ s.filters.each { |f| part << "." << f.describe }
287
+ case s.index
288
+ when nil then nil
289
+ when 0 then part << ".first()"
290
+ when -1 then part << ".last()"
291
+ else part << ".nth(#{s.index})"
292
+ end
293
+ if out.empty?
294
+ out = part.sub(/\A\.+/, "")
295
+ elsif part.start_with?(".")
296
+ out << part
297
+ else
298
+ out << "." << part
299
+ end
300
+ end
301
+ out
302
+ end
303
+
304
+ # The chain in the engine's wire form; an unparsable selector raises here.
305
+ def wire_checked
306
+ steps.each_with_index.map do |s, i|
307
+ if s.capture && !s.index.nil?
308
+ raise Query::InvalidSelector, "Error: Can't query n-th element in a request with the capture."
309
+ end
310
+
311
+ q = s.query.wire
312
+ # A frame hop names its <iframe> locator in errors.
313
+ q["d"] = Chain.new(steps[0...i]).describe if s.query.kind == :frame
314
+ { "q" => q, "f" => s.filters.map(&:wire), "i" => s.index }
315
+ end
316
+ end
317
+
318
+ # The wire form, for nested chains where an error surfaces later.
319
+ def wire
320
+ wire_checked
321
+ rescue Query::InvalidSelector
322
+ []
323
+ end
324
+
325
+ def then(step)
326
+ Chain.new(steps.map(&:dup_step) + [step])
327
+ end
328
+
329
+ def then_all(more)
330
+ Chain.new(steps.map(&:dup_step) + more.steps.map(&:dup_step))
331
+ end
332
+
333
+ # The same chain with the block applied to its last step (an index, a
334
+ # filter), or a self step added when that step already has an index.
335
+ def with_last
336
+ s = steps.map(&:dup_step)
337
+ s << Step.new(Query.new(:self)) if s.empty? || !s.last.index.nil?
338
+ yield s.last
339
+ Chain.new(s)
340
+ end
341
+ end
342
+ end
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "testsurfer"
4
+
5
+ module Testsurfer
6
+ # RSpec matchers for the web-first assertions:
7
+ #
8
+ # require "testsurfer/rspec"
9
+ # RSpec.configure { |c| c.include Testsurfer::RSpec::Matchers }
10
+ #
11
+ # expect(page.get_by_role("heading")).to have_text("Dashboard")
12
+ # expect(page.locator(".spinner")).not_to be_visible
13
+ # expect(page).to have_url(/dashboard/)
14
+ #
15
+ # Each matcher is `to_<name>` of Testsurfer.expect: `have_text`,
16
+ # `be_visible`, `have_count`, ... with the same arguments and `timeout:`.
17
+ # On anything but a Locator or a Page, `be_*` and `have_*` matchers
18
+ # fall back to RSpec's own predicate matchers.
19
+ module RSpec
20
+ NAMES = %w[
21
+ be_attached be_checked be_disabled be_editable be_empty be_enabled be_focused be_hidden be_in_viewport
22
+ be_unchecked be_visible contain_class contain_text have_accessible_description have_accessible_name
23
+ have_attribute have_class have_count have_css have_id have_js_property have_role have_screenshot
24
+ have_text have_title have_url have_value have_values match_aria_snapshot
25
+ ].freeze
26
+
27
+ # One web-first matcher.
28
+ class Matcher
29
+ def initialize(name, args, kwargs)
30
+ @name = name
31
+ @args = args
32
+ @kwargs = kwargs
33
+ @message = nil
34
+ end
35
+
36
+ def matches?(actual)
37
+ return fallback.matches?(actual) if foreign?(actual)
38
+
39
+ run(actual, "to_#{@name}")
40
+ end
41
+
42
+ def does_not_match?(actual)
43
+ if foreign?(actual)
44
+ f = fallback
45
+ return f.respond_to?(:does_not_match?) ? f.does_not_match?(actual) : !f.matches?(actual)
46
+ end
47
+
48
+ run(actual, "not_to_#{@name}")
49
+ end
50
+
51
+ def failure_message
52
+ @fallback ? @fallback.failure_message : @message
53
+ end
54
+
55
+ def failure_message_when_negated
56
+ @fallback ? @fallback.failure_message_when_negated : @message
57
+ end
58
+
59
+ def description
60
+ "#{@name.tr('_', ' ')}#{@args.empty? ? '' : " #{@args.map(&:inspect).join(', ')}"}"
61
+ end
62
+
63
+ def supports_block_expectations?
64
+ false
65
+ end
66
+
67
+ private
68
+
69
+ def foreign?(actual)
70
+ !actual.is_a?(Locator) && !actual.is_a?(Page)
71
+ end
72
+
73
+ def run(actual, method)
74
+ Testsurfer.expect(actual).public_send(method, *@args, **@kwargs)
75
+ true
76
+ rescue AssertionError => e
77
+ @message = e.message
78
+ false
79
+ end
80
+
81
+ def fallback
82
+ @fallback ||= if @name.start_with?("be_")
83
+ ::RSpec::Matchers::BuiltIn::BePredicate.new(@name.to_sym, *@args, **@kwargs)
84
+ elsif @name.start_with?("have_")
85
+ ::RSpec::Matchers::BuiltIn::Has.new(@name.to_sym, *@args, **@kwargs)
86
+ else
87
+ raise UsageError, "#{@name} needs a Testsurfer::Locator or Testsurfer::Page"
88
+ end
89
+ end
90
+ end
91
+
92
+ module Matchers
93
+ NAMES.each do |n|
94
+ define_method(n) { |*args, **kwargs| Matcher.new(n, args, kwargs) }
95
+ end
96
+ end
97
+ end
98
+ end