23

I have a select box, with a label:

<label for="slide_orientation">Slide orientation</label>
<select disabled="" class="property" id="slide_orientation" name="slide_orientation">
  <option value="horizontal">Horizontal</option>
  <option value="vertical" selected="selected">Vertical</option>
</select>

As you can see the select box is disabled. When I try to find it with field_labeled("Slide orientation"), it returns an error:

Capybara::ElementNotFound: Unable to find field "Slide orientation"
from /Users/pascal/.rvm/gems/ruby-1.9.3-p392/gems/capybara-2.0.2/lib/capybara/result.rb:22:in `find!'

When the select box is not disabled, field_labeled("Slide orientation") returns the select element just fine.

Is this expected behavior? And if so, how would I go about finding a disabled element? In my case I need it to test if it's disabled or not.

Pascal Lindelauf
  • 4,782
  • 4
  • 40
  • 55

4 Answers4

38

Capybara 2.1.0 supports disabled filter. You can easily find disabled fields with it.

field_labeled("Slide orientation", disabled: true)

You need to specify it explicitly because the disabled filter is off by default.

Shuhei Kagawa
  • 4,752
  • 1
  • 33
  • 31
11

This one passes if it has the disabled attribute.

Run with js: true and page.evaluate_script.

it "check slider orientation", js: true do
    disabled = page.evaluate_script("$('#slide_orientation').attr('disabled');")
    disabled.should == 'disabled' 
end

Update

or you can use have_css

page.should have_css("#slide_orientation[disabled]") 

(stolen form this excellent answer )

Community
  • 1
  • 1
Andreas Lyngstad
  • 4,887
  • 2
  • 36
  • 69
8

Since the answers to this are old and things have moved on a little since then here is an UPDATE.

If you just want to check if a field is disabled you can now do:

expect(page).to have_field 'Slide orientation', disabled: true

As per this PR: https://github.com/teamcapybara/capybara/issues/982

rmaspero
  • 573
  • 2
  • 11
  • 23
3

Andreas and this answer put me on the track to the final solution. Finding a disabled field with a certain label (instead of HTML id) can be achieved this way:

label_field = all("label").detect { |l| (l.text =~ /#{label}/i).present? }
raise Exception.new("Couldn't find field '#{label}'") if label_field.nil?
the_actual_field = first("##{label_field[:for]}")

Checking if that field is disabled can be done with one statement:

page.should have_css("##{label_field[:for]}[disabled]") 

It still feels like a workaround instead of the best Capybara-like solution, but it works!

Community
  • 1
  • 1
Pascal Lindelauf
  • 4,782
  • 4
  • 40
  • 55