Skip to content

Commit 169b479

Browse files
committed
issue#58 implement Node#selected
1 parent be75207 commit 169b479

File tree

2 files changed

+39
-7
lines changed

2 files changed

+39
-7
lines changed

lib/ferrum/node.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,18 @@ def attribute(name)
127127
evaluate("this.getAttribute('#{name}')")
128128
end
129129

130+
def selected
131+
function = <<~JS
132+
function(element) {
133+
if (element.nodeName.toLowerCase() !== 'select') {
134+
throw new Error('Element is not a <select> element.');
135+
}
136+
return Array.from(element).filter(option => option.selected).map((option) => option.text);
137+
}
138+
JS
139+
page.evaluate_func(function, self)
140+
end
141+
130142
def evaluate(expression)
131143
page.evaluate_on(node: self, expression: expression)
132144
end

spec/node_spec.rb

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -83,13 +83,33 @@ module Ferrum
8383
expect(links.first.text).to eq("Open for match")
8484
end
8585

86-
it "picks option in select" do
87-
browser.goto("/ferrum/form")
88-
input = browser.at_xpath("//*[@id='form_title']")
89-
expect(input.value).to eq "Mrs"
90-
input.click
91-
input.type("Miss", :Enter)
92-
expect(input.value).to eq "Miss"
86+
describe "#selected" do
87+
before do
88+
browser.goto("/ferrum/form")
89+
end
90+
91+
it "returns texts of selected options" do
92+
expect(browser.at_xpath("//*[@id='form_region']").selected).to eq(["Norway"])
93+
end
94+
95+
context "when options exists but no selected option" do
96+
it "returns first option text as default value" do
97+
expect(browser.at_xpath("//*[@id='form_title']").selected).to eq(["Mrs"])
98+
end
99+
end
100+
101+
context "when no selected options" do
102+
it "returns empty array" do
103+
expect(browser.at_xpath("//*[@id='form_tendency']").selected).to eq([])
104+
end
105+
end
106+
107+
context "when selector is not <select>" do
108+
it "raises JavaScriptError with proper message" do
109+
expect { browser.at_xpath("//*[@id='customer_name']").selected }.
110+
to raise_exception(Ferrum::JavaScriptError, /Element is not a <select> element/)
111+
end
112+
end
93113
end
94114

95115
context "when the element is not in the viewport" do

0 commit comments

Comments
 (0)