File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change @@ -139,6 +139,30 @@ def selected
139
139
page . evaluate_func ( function , self )
140
140
end
141
141
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
+
142
166
def evaluate ( expression )
143
167
page . evaluate_on ( node : self , expression : expression )
144
168
end
Original file line number Diff line number Diff line change @@ -112,6 +112,33 @@ module Ferrum
112
112
end
113
113
end
114
114
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
+
115
142
context "when the element is not in the viewport" do
116
143
before do
117
144
browser . go_to ( "/ferrum/with_js" )
You can’t perform that action at this time.
0 commit comments