Search code examples
ruby-on-railsrubyrspecrefactoringcapybara-webkit

Variable name with another variable value on it to achieve less repetitions


I'm working on the refactor of my RSpec+ capybara-webkit tests, and I I'm trying to not have lot of repetitions.
So I created this method that I will call various times during the tests:

def fill(field1, value1, field2, value2, field3, value3, button)
 fill_in field1, :with => value1
 fill_in field2, :with => value2
 fill_in field3, :with => value3
 find(button).click
end

And this is my test:

describe "Test", :js => true do
 it "fill fields" do
  fill('first_field', 'first_value', 'second_field', 'second_value, 'third_field', 'third_value', 'input.button')
 end
end

I'd like to have something very simple like

def fill(field1, value1, field2, value2, field3, value3, button)
 for i in 1..3 do
  fill_in field+"#{i}", :with => value+"#{i}"
 end
 find(button).click
end

but I cannot achieve it so easily.

I tried also with

def fill(field1, value1, field2, value2, field3, value3, button)
 for i in 1..3 do
  fill_in "field#{i}", :with => "value#{i}"
 end
 find(button).click
end

but RSpec will search for a field called "field1" and not for "first_field" (that I'm passing to the method).


Solution

  • You should pass a hash of fields and values:

    def fill(button, h)
      h.each{|field, value| fill_in field, with: value}
      find(button).click
    end
    
    describe "Test", js: true do
      it "fill fields" do
        fill('input.button', 'first_field' => 'first_value', 'second_field' => 'second_value', 'third_field' => 'third_value')
      end
    end