Search code examples
ruby-on-railsselenium-webdrivertestingrspeccapybara

How to set an attribute value with Capybara, Selenium and the like?


I've a <textarea> field (a Rails model attribute) for which I've to test that the allowed max length error message is displayed. I've to make that using a system spec with Capybara, Selenium and the like enabled.

# model
class Model < ActiveRecord::Base
  validates_length_of :description, maximum: 1000
end

# view
<label for="description">Description</label>
<textarea maxlength="1000" id="description">Some text</textarea>

# RSpec
RSpec.describe "Model", type: :system do
  it "should fail" do
    visit edit_model_path(@model)

    fill_in "Description", with: "abcdefghijklmnopqrstuvwxyz"*1000

    # ...
  end
end

I tried to fill in the <textarea> with a text longer than 1000 chars and, as well (maxlength="1000"), it inserts into <textarea> only the first 1000 chars of the text, which makes me not able to test the max length error message output.

I thought one way to test that is to change the maxlength attribute of the <textarea> right in the RSpec example so I can fill in it more than 1000 chars, making me able to effectively test the max length error.

Is it possible with RSpec Capybara, Selenium and the like to change the maxlength attribute?


Solution

  • Based on @max comment, here is a (arguable for testing) way to change the maxlength attribute of the <textarea> right in the RSpec by using Selenium:

    # RSpec
    RSpec.describe "Model", type: :system do
      it "should fail" do
        # ...
    
        page.execute_script("document.getElementById('description').removeAttribute('maxlength')");
    
        # ...
      end
    end