2
0
Fork 0
mirror of https://github.com/discourse/discourse.git synced 2026-03-05 15:27:34 +08:00
discourse/spec/support/computed_style_matcher.rb
Jarek Radosz b81f4104ef
DEV: Normalize (ok)lch values in computed style matcher (#36404)
We can't compare **computed** (ok)lch values since those are not stable.
For example, one of the values used in "User color palette selector"
spec:

* `oklch(0.92 0.0708528 68.5036)` - the value hardcoded in the spec
* `oklch(0.92 0.0708528 68.5037)` - the value on my machine (the spec
was failing)
* `oklch(0.92 0.070857 68.5063)` - the value after updating pitchfork
(that's why the [PR](https://github.com/discourse/discourse/pull/36352)
is failing)

All those are effectively the same. When converted to hex they all
resolve to `#ffddb2`.
2025-12-03 02:13:09 +01:00

43 lines
1.2 KiB
Ruby

# frozen_string_literal: true
RSpec::Matchers.define :have_computed_style do |expected|
match do |element|
actual = normalize(computed_style(element, expected.keys.first))
actual == normalize(expected.values.first)
end
failure_message do |element|
actual = computed_style(element, expected.keys.first)
"expected the element to have #{expected.keys.first} with the value '#{expected.values.first}', but the value is '#{actual}'"
end
failure_message_when_negated do |element|
"expected the element not to have #{expected.keys.first} with the value #{expected.values.first}, but it does"
end
def computed_style(element, property)
element.evaluate_script("getComputedStyle(this)['#{property}']")
end
def normalize(value)
match =
/
\A(?<prefix>(?:ok)?lch)
\(
(?<l>.+)(?<symbol>%?)\s
(?<c>.+)\s
(?<h>.+)
\)\Z
/x.match(
value,
)
return value if !match
l = format("%.2f", BigDecimal(match[:l]).truncate(2))
c = format("%.2f", BigDecimal(match[:c]).truncate(2))
h = format("%.2f", BigDecimal(match[:h]).truncate(2))
"#{match[:prefix]}(#{l}#{match[:symbol]} #{c} #{h})"
end
end