Skip to content

Commit 790e6f9

Browse files
committed

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

lib/ferrum/node.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,30 @@ def selected
139139
page.evaluate_func(function, self)
140140
end
141141

142+
def select(*values)
143+
tap do
144+
function = <<~JS
145+
function(element, values) {
146+
if (element.nodeName.toLowerCase() !== 'select') {
147+
throw new Error('Element is not a <select> element.');
148+
}
149+
const options = Array.from(element.options);
150+
element.value = undefined;
151+
for (const option of options) {
152+
option.selected = values.includes(option.value);
153+
if (option.selected && !element.multiple) break;
154+
}
155+
element.dispatchEvent(new Event('input', { bubbles: true }));
156+
element.dispatchEvent(new Event('change', { bubbles: true }));
157+
return options
158+
.filter((option) => option.selected)
159+
.map((option) => option.value);
160+
}
161+
JS
162+
page.evaluate_func(function, self, values.join(','))
163+
end
164+
end
165+
142166
def evaluate(expression)
143167
page.evaluate_on(node: self, expression: expression)
144168
end

spec/node_spec.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,33 @@ module Ferrum
112112
end
113113
end
114114

115+
describe "#select" do
116+
before do
117+
browser.goto("/ferrum/form")
118+
end
119+
120+
it "picks option in select by match string argument" do
121+
expect(browser.at_xpath("//*[@id='form_title']").select("Miss").value).to eq("Miss")
122+
end
123+
124+
context "when select has multiple property" do
125+
it "picks options in select by match arguments as array" do
126+
expect(browser.at_xpath("//*[@id='form_languages']").select(%w[SQL Ruby]).selected).to eq(%w[Ruby SQL])
127+
end
128+
129+
it "picks options in select by match arguments as string" do
130+
expect(browser.at_xpath("//*[@id='form_languages']").select("SQL, Ruby").selected).to eq(%w[Ruby SQL])
131+
end
132+
end
133+
134+
context "when selector is not <select>" do
135+
it "raises JavaScriptError with proper message" do
136+
expect { browser.at_xpath("//*[@id='customer_name']").select(anything) }.
137+
to raise_exception(Ferrum::JavaScriptError, /Element is not a <select> element/)
138+
end
139+
end
140+
end
141+
115142
context "when the element is not in the viewport" do
116143
before do
117144
browser.go_to("/ferrum/with_js")

0 commit comments

Comments
 (0)