diff --git a/Rakefile b/Rakefile index ad0f15e..9f98398 100644 --- a/Rakefile +++ b/Rakefile @@ -12,7 +12,7 @@ unless ARGV.any? {|a| a =~ /^gems/} gem 'cucumber', '> 0.3.101', '<= 0.5.0' require 'cucumber/rake/task' namespace :mundo_pepino do - build_tasks = [:lib, :rails_generators, :en_US, :es_ES] + build_tasks = [:lib, :rails_generators, :en_US, :es_ES, :capybara_en_US, :capybara_es_ES] build_tasks.each do |lang| Cucumber::Rake::Task.new(lang) do |t| t.cucumber_opts = "--profile #{lang} --format pretty" diff --git a/cucumber.yml b/cucumber.yml index ab15230..533b08e 100644 --- a/cucumber.yml +++ b/cucumber.yml @@ -2,3 +2,6 @@ lib: -r features/support/env.rb -r features/step_definitions/lib_steps.rb featur es_ES: --require features/support/env.rb --require features/step_definitions/es_ES.rb features/es_ES/ en_US: --require features/support/env.rb --require features/step_definitions/en_US.rb features/en_US/ rails_generators: -r features/support/rails_generators_env.rb -r features/step_definitions/rails_generators_steps.rb features/rails_generators/ + +capybara_es_ES: --require features/support/capybara/env.rb --require features/step_definitions/es_ES.rb features/es_ES/ +capybara_en_US: --require features/support/capybara/env.rb --require features/step_definitions/en_US.rb features/en_US/ diff --git a/features/es_ES/cuando-adjunto-el-fichero.feature b/features/es_ES/cuando-adjunto-el-fichero.feature index 10819e6..90c78b8 100644 --- a/features/es_ES/cuando-adjunto-el-fichero.feature +++ b/features/es_ES/cuando-adjunto-el-fichero.feature @@ -13,11 +13,11 @@ Característica: adjunto el fichero ######################################################################## Cuando visito la portada Y adjunto el fichero "Rakefile" en Fichero Adjunto - Y pincho en el botón "Galleta de la fortuna" + Y pincho en el botón "Galleta de la Fortuna" Entonces veo en la etiqueta div#file_filename el valor "Rakefile" Escenario: Adjunto un fichero local en un campo de formulario (como Given) Dado que visito la portada Y que adjunto el fichero "Rakefile" en Fichero Adjunto - Cuando pincho en el botón "Galleta de la fortuna" + Cuando pincho en el botón "Galleta de la Fortuna" Entonces veo en la etiqueta div#file_filename el valor "Rakefile" diff --git a/features/es_ES/cuando-elijo-de-radiobutton.feature b/features/es_ES/cuando-elijo-de-radiobutton.feature index 8c6e433..16ddb8c 100644 --- a/features/es_ES/cuando-elijo-de-radiobutton.feature +++ b/features/es_ES/cuando-elijo-de-radiobutton.feature @@ -34,16 +34,16 @@ Característica: elijo radiobutton ######################################################################## Cuando visito la portada Y elijo la nacionalidad "Pakistaní" - Y pincho el botón "Galleta de la fortuna" + Y pincho el botón "Galleta de la Fortuna" Entonces veo el tag div#nationality con el valor "Pakistaní" Cuando visito la portada Y elijo "Verde" - Y pincho el botón "Galleta de la fortuna" + Y pincho el botón "Galleta de la Fortuna" Entonces veo el tag div#color con el valor "verde" Escenario: Elijo una opción de un radiobutton (desde Given) Dado que visito la portada Y que elijo como color "VERDE" - Cuando pincho el botón "Galleta de la fortuna" + Cuando pincho el botón "Galleta de la Fortuna" Entonces veo el tag div#color con el valor "verde" diff --git a/features/es_ES/cuando-marco-el-checkbox.feature b/features/es_ES/cuando-marco-el-checkbox.feature index ffdba77..386f63e 100644 --- a/features/es_ES/cuando-marco-el-checkbox.feature +++ b/features/es_ES/cuando-marco-el-checkbox.feature @@ -20,7 +20,7 @@ Característica: marco el checkbox ######################################################################## # Pre-checking Cuando visito la portada - Y pincho en el botón "Galleta de la fortuna" + Y pincho en el botón "Galleta de la Fortuna" Entonces veo el tag div#selected_check con el valor "Seleccionado" Y no veo el tag div#unselected_check con el valor "Sin seleccionar" @@ -28,7 +28,7 @@ Característica: marco el checkbox Cuando visito la portada Y desmarco la casilla seleccionada Y marco la casilla sin seleccionar - Y pincho en el botón "Galleta de la fortuna" + Y pincho en el botón "Galleta de la Fortuna" Entonces no veo el tag div#selected_check con el valor "Seleccionado" Y veo el tag div#unselected_check con el valor "Sin seleccionar" @@ -36,6 +36,6 @@ Característica: marco el checkbox Dado que visito la portada Y que desmarco la casilla seleccionada Y que marco la casilla sin seleccionar - Cuando pincho en el botón "Galleta de la fortuna" + Cuando pincho en el botón "Galleta de la Fortuna" Entonces no veo el tag div#selected_check con el valor "Seleccionado" Y veo el tag div#unselected_check con el valor "Sin seleccionar" diff --git a/features/es_ES/cuando-pulso-los-siguientes-enlaces-y-botones.feature b/features/es_ES/cuando-pulso-los-siguientes-enlaces-y-botones.feature index 9792201..f4af59b 100644 --- a/features/es_ES/cuando-pulso-los-siguientes-enlaces-y-botones.feature +++ b/features/es_ES/cuando-pulso-los-siguientes-enlaces-y-botones.feature @@ -39,12 +39,12 @@ Característica: pulso una secuencia de enlaces y/o botones Dado que visito la home Y que pulso en los siguientes enlaces y botones: | tipo | nombre | - | botón | Galleta de la fortuna | + | botón | Galleta de la Fortuna | | enlace | Volver | Y que pulso en los siguientes botones y enlaces: | tipo | nombre | - | botón | Galleta de la fortuna | + | botón | Galleta de la Fortuna | | enlace | Volver | - | botón | Galleta de la fortuna | + | botón | Galleta de la Fortuna | Entonces veo la etiqueta H1 con el valor "Sorry, not implemented yet" diff --git a/features/es_ES/cuando-relleno-el-campo.feature b/features/es_ES/cuando-relleno-el-campo.feature index 4209c95..18bc550 100644 --- a/features/es_ES/cuando-relleno-el-campo.feature +++ b/features/es_ES/cuando-relleno-el-campo.feature @@ -21,21 +21,21 @@ Característica: relleno el campo ######################################################################## Cuando visito la portada Y relleno "campo de texto" con "Fertilizador" - Y pincho en el botón "Galleta de la fortuna" + Y pincho en el botón "Galleta de la Fortuna" Entonces veo el tag div#text_field con el valor "Fertilizador" Cuando visito la portada Y completo Campo de texto con el valor "Berenjenas" - Y pincho en el botón "Galleta de la fortuna" + Y pincho en el botón "Galleta de la Fortuna" Entonces veo el tag div#text_field con el valor "Berenjenas" Cuando visito la portada Y completo "área de texto" con el valor "Garbanzos" - Y pincho en el botón "Galleta de la fortuna" + Y pincho en el botón "Galleta de la Fortuna" Entonces veo el tag div#textarea con el valor "Garbanzos" Escenario: Relleno un campo con un texto (desde Given) Dado que visito la portada Y que completo "área de texto" con el valor "Garbanzos" - Cuando pincho en el botón "Galleta de la fortuna" + Cuando pincho en el botón "Galleta de la Fortuna" Entonces veo el tag div#textarea con el valor "Garbanzos" diff --git a/features/es_ES/cuando-relleno-los-campos.feature b/features/es_ES/cuando-relleno-los-campos.feature index a9662d1..6aa0d01 100644 --- a/features/es_ES/cuando-relleno-los-campos.feature +++ b/features/es_ES/cuando-relleno-los-campos.feature @@ -24,7 +24,7 @@ Característica: relleno los campos | Campo | Valor | | campo de texto | Fertilizador | | área de texto | Garbanzos | - Y pincho en el botón "Galleta de la fortuna" + Y pincho en el botón "Galleta de la Fortuna" Entonces veo el tag div#text_field con el valor "Fertilizador" Y veo el tag div#textarea con el valor "Garbanzos" Ejemplos: diff --git a/features/es_ES/cuando-selecciono-en-listado.feature b/features/es_ES/cuando-selecciono-en-listado.feature index fe16c3e..43eb459 100644 --- a/features/es_ES/cuando-selecciono-en-listado.feature +++ b/features/es_ES/cuando-selecciono-en-listado.feature @@ -17,22 +17,22 @@ Característica: selecciono en listado/s ######################################################################## Cuando visito la portada Y selecciono "Hortalizas" en el listado de "Tipos de cultivo" - Y pulso el botón "Galleta de la fortuna" + Y pulso el botón "Galleta de la Fortuna" Entonces veo el tag div#orchard_type con el valor "Hortalizas" Cuando visito la portada Y selecciono 'Frutales' en Tipos de Cultivo - Y pulso el botón "Galleta de la fortuna" + Y pulso el botón "Galleta de la Fortuna" Entonces veo el tag div#orchard_type con el valor "Frutales" Cuando visito la portada Y selecciono 'Frutales' como Tipos de Cultivo - Y pulso el botón "Galleta de la fortuna" + Y pulso el botón "Galleta de la Fortuna" Entonces veo el tag div#orchard_type con el valor "Frutales" Cuando visito la portada Y selecciono 'Hortalizas' - Y pulso el botón "Galleta de la fortuna" + Y pulso el botón "Galleta de la Fortuna" Entonces veo el tag div#orchard_type con el valor "Hortalizas" Escenario: Selecciono una fecha y hora sin indicar un campo específico @@ -57,12 +57,12 @@ Característica: selecciono en listado/s # (continua más abajo) Cuando visito la portada Y selecciono "25 de diciembre de 2008, 10:00" como fecha y hora - Y pulso el botón "Galleta de la fortuna" + Y pulso el botón "Galleta de la Fortuna" Entonces veo el tag div#fecha-preferida con el valor "25/12/2008" Y veo el tag div#hora-preferida con el valor "10:00" Cuando visito la portada Y selecciono 1 de setiembre de 1998, 12:46" como fecha y hora - Y pulso el botón "Galleta de la fortuna" + Y pulso el botón "Galleta de la Fortuna" Entonces veo el tag div#fecha-preferida con el valor "1/9/1998" Y veo el tag div#hora-preferida con el valor "12:46" @@ -100,7 +100,7 @@ Característica: selecciono en listado/s Cuando visito la portada Y selecciono "23 de noviembre de 2004, 11:20" como fecha y hora Preferida Y selecciono 25 de enero de 2005, 10:30 como fecha y hora de "Alternativa" - Y pulso el botón "Galleta de la fortuna" + Y pulso el botón "Galleta de la Fortuna" Entonces veo el tag div#fecha-preferida con el valor "23/11/2004" Y veo el tag div#hora-preferida con el valor "11:20" Y veo el tag div#fecha-alternativa con el valor "25/1/2005" @@ -126,12 +126,12 @@ Característica: selecciono en listado/s # (continua más abajo) Cuando visito la portada Y selecciono 16:23 como hora - Y pulso el botón "Galleta de la fortuna" + Y pulso el botón "Galleta de la Fortuna" Entonces veo el tag div#hora-preferida con el valor "16:23" Cuando visito la portada Y selecciono "4:23PM" como hora - Y pulso el botón "Galleta de la fortuna" + Y pulso el botón "Galleta de la Fortuna" Entonces veo el tag div#hora-preferida con el valor "16:23" Escenario: Selecciono una hora para un campo específico @@ -180,12 +180,12 @@ Característica: selecciono en listado/s # (continua más abajo) Cuando visito la portada Y selecciono "28 de marzo de 2005" como fecha - Y pulso el botón "Galleta de la fortuna" + Y pulso el botón "Galleta de la Fortuna" Entonces veo el tag div#fecha-preferida con el valor "28/3/2005" Cuando visito la portada Y selecciono "2 de agosto de 2008" como la fecha - Y pulso el botón "Galleta de la fortuna" + Y pulso el botón "Galleta de la Fortuna" Entonces veo el tag div#fecha-preferida con el valor "2/8/2008" Escenario: Selecciono una fecha para un campo específico @@ -210,7 +210,7 @@ Característica: selecciono en listado/s Cuando visito la portada Y selecciono 1 de octubre de 2009 como fecha para la vendimia Y selecciono 15 de marzo de 2010 como fecha de "poda" - Y pulso el botón "Galleta de la fortuna" + Y pulso el botón "Galleta de la Fortuna" Entonces veo el tag div#fecha-de-vendimia con el valor "1/10/2009" Y veo el tag div#fecha-de-poda con el valor "15/3/2010" @@ -220,7 +220,7 @@ Característica: selecciono en listado/s Y que selecciono "23 de noviembre de 2009, 11:20" como fecha y hora "Alternativa" Y que selecciono 1 de marzo de 2009 como fecha de la poda Y que selecciono 'Hortalizas' - Cuando pulso el botón "Galleta de la fortuna" + Cuando pulso el botón "Galleta de la Fortuna" Entonces veo el tag div#orchard_type con el valor "Hortalizas" Y veo el tag div#fecha-preferida con el valor "25/1/2009" Y veo el tag div#hora-preferida con el valor "10:30" diff --git a/features/support/app/config/locales/es.yml b/features/support/app/config/locales/es.yml index 648ff39..7ec4b3b 100644 --- a/features/support/app/config/locales/es.yml +++ b/features/support/app/config/locales/es.yml @@ -158,5 +158,5 @@ es: app: welcome: title: 'Portada de Mundo Pepino' - cookie_fortune: 'Galleta de la fortuna' + cookie_fortune: 'Galleta de la Fortuna' interpolated: 'Mensaje con {{name}}' diff --git a/features/support/capybara/capextensions.rb b/features/support/capybara/capextensions.rb new file mode 100644 index 0000000..ae8ffaf --- /dev/null +++ b/features/support/capybara/capextensions.rb @@ -0,0 +1,126 @@ +module Capextensions + + DATE_TIME_SUFFIXES = { + :year => '1i', + :month => '2i', + :day => '3i', + :hour => '4i', + :minute => '5i' + } + + def click_link_within(selector, link_text) + within(:css, selector) do + click_link link_text + end + end + + def select_date(date_to_select, options={}) + date = date_to_select.is_a?(Date) || date_to_select.is_a?(Time) ? + date_to_select : Date.parse(date_to_select) + + if options[:id_prefix].blank? + if options[:from].blank? + source = locate(:xpath, Capybara::XPath.append("//select[contains(@id, '_#{DATE_TIME_SUFFIXES[:year]}')]")) + id_prefix = source.node.attributes["id"].value[/(.*?)_#{DATE_TIME_SUFFIXES[:year]}$/, 1] + else + msg = "cannot select option, no select box with id, name, or label '#{options[:from]}' found" + begin + label = locate(:xpath, Capybara::XPath.append("//label[text()='#{options[:from]}']"), msg) + id_prefix = label.node.attributes["for"].value + rescue Capybara::ElementNotFound + begin + previous_exception = $! + label = locate(:xpath, Capybara::XPath.append("//label[text()='#{options[:from].capitalize}']"), msg) + id_prefix = label.node.attributes["for"].value + rescue + raise "#{previous_exception}\nand\n#{$!}" + end + end + end + end + + id_prefix ||= options[:id_prefix] + + select date.year, :from => "#{id_prefix}_#{DATE_TIME_SUFFIXES[:year]}" + select date.strftime('%B'), :from => "#{id_prefix}_#{DATE_TIME_SUFFIXES[:month]}" + select date.day, :from => "#{id_prefix}_#{DATE_TIME_SUFFIXES[:day]}" + end + + def select_time(time_to_select, options ={}) + time = time_to_select.is_a?(Time) ? time_to_select : Time.parse(time_to_select) + + if options[:id_prefix].blank? + if options[:from].blank? + source = locate(:xpath, Capybara::XPath.append("//select[contains(@id, '_#{DATE_TIME_SUFFIXES[:hour]}')]")) + id_prefix = source.node.attributes["id"].value[/(.*?)_#{DATE_TIME_SUFFIXES[:hour]}$/, 1] + else + msg = "cannot select option, no select box with id, name, or label '#{options[:from]}' found" + begin + label = locate(:xpath, Capybara::XPath.append("//label[text()='#{options[:from]}']"), msg) + id_prefix = label.node.attributes["for"].value + rescue Capybara::ElementNotFound + begin + previous_exception = $! + label = locate(:xpath, Capybara::XPath.append("//label[text()='#{options[:from].capitalize}']"), msg) + id_prefix = label.node.attributes["for"].value + rescue + raise "#{previous_exception}\nand\n#{$!}" + end + end + end + end + + id_prefix ||= options[:id_prefix] + + select time.hour.to_s.rjust(2, '0'), :from => "#{id_prefix}_#{DATE_TIME_SUFFIXES[:hour]}" + select time.min.to_s.rjust(2, '0'), :from => "#{id_prefix}_#{DATE_TIME_SUFFIXES[:minute]}" + end + + def select_datetime(time_to_select, options={}) + time = time_to_select.is_a?(Time) ? time_to_select : Time.parse(time_to_select) + + if options[:from] + msg = "cannot select option, no select box with id, name, or label '#{options[:from]}' found" + begin + label = locate(:xpath, Capybara::XPath.append("//label[text()='#{options[:from]}']"), msg) + id_prefix = label.node.attributes["for"].value + rescue Capybara::ElementNotFound + begin + previous_exception = $! + label = locate(:xpath, Capybara::XPath.append("//label[text()='#{options[:from].capitalize}']"), msg) + id_prefix = label.node.attributes["for"].value + rescue + raise "#{previous_exception}\nand\n#{$!}" + end + end + end + + options[:id_prefix] ||= (options[:from] ? id_prefix : nil) + + select_date time, options + select_time time, options + end + + # Maybe this methos should be defined in the other order, capybara is the default? + def response(*args, &block) + page(*args, &block) + end + + def have_tag(*args, &block) + text = args[1] + unless text.blank? + have_css(args.first, :text => text) + else + have_css(args.first) + end + end + + def have_selector(path, options = {}) + # content key to text key + content = options.delete(:content) + options[:text] = content unless content.nil? + have_css(path, options) + end +end + +World(Capextensions) \ No newline at end of file diff --git a/features/support/capybara/env.rb b/features/support/capybara/env.rb new file mode 100644 index 0000000..3c97208 --- /dev/null +++ b/features/support/capybara/env.rb @@ -0,0 +1,47 @@ +# Sets up the Rails environment for Cucumber +ENV["RAILS_ENV"] ||= "cucumber" +require File.expand_path(File.dirname(__FILE__) + '/../app/config/environment') + +require 'ruby-debug' + +require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support +require 'cucumber/rails/world' +require 'cucumber/rails/rspec' +require 'cucumber/rails/active_record' +require 'cucumber/web/tableish' + +require 'capybara/rails' +require 'capybara/cucumber' +require 'capybara/session' +require 'cucumber/rails/capybara_javascript_emulation' # Lets you click links with onclick javascript handlers without using @culerity or @javascript +# Capybara defaults to XPath selectors rather than Webrat's default of CSS3. In +# order to ease the transition to Capybara we set the default here. If you'd +# prefer to use XPath just remove this line and adjust any selectors in your +# steps to use the XPath syntax. +Capybara.default_selector = :css + +require File.expand_path(File.dirname(__FILE__) + '/capextensions') + +# Whether or not to allow Rails to rescue errors and render them on +# an error page. Default is false, which will cause an error to be +# raised. +# +# If you leave this to false, you can turn on Rails rescuing on a +# per-scenario basis, simply tagging it with @allow-rescue +ActionController::Base.allow_rescue = false + +# Whether or not to run each scenario within a database transaction. +# +# If you leave this to true, you can turn off traqnsactions on a +# per-scenario basis, simply tagging it with @no-txn +Cucumber::Rails::World.use_transactional_fixtures = true + +# How to clean your database when transactions are turned off. See +# http://github.com/bmabey/database_cleaner for more info. +if defined?(ActiveRecord::Base) + begin + require 'database_cleaner' + DatabaseCleaner.strategy = :truncation + rescue LoadError => ignore_if_database_cleaner_not_present + end +end \ No newline at end of file diff --git a/features/support/env.rb b/features/support/env.rb index 69eae31..c6ae8ce 100644 --- a/features/support/env.rb +++ b/features/support/env.rb @@ -1,19 +1,21 @@ # Sets up the Rails environment for Cucumber ENV["RAILS_ENV"] ||= "cucumber" require File.expand_path(File.dirname(__FILE__) + '/app/config/environment') - + require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support -require 'cucumber/rails/rspec' require 'cucumber/rails/world' +require 'cucumber/rails/rspec' require 'cucumber/rails/active_record' require 'cucumber/web/tableish' - -# Whether or not to run each scenario within a database transaction. -# -# If you leave this to true, you can turn off traqnsactions on a -# per-scenario basis, simply tagging it with @no-txn -Cucumber::Rails::World.use_transactional_fixtures = true - + +require 'webrat' +require 'webrat/core/matchers' + +Webrat.configure do |config| + config.mode = :rails + config.open_error_files = false # Set to true if you want error pages to pop up in the browser +end + # Whether or not to allow Rails to rescue errors and render them on # an error page. Default is false, which will cause an error to be # raised. @@ -21,13 +23,19 @@ # If you leave this to false, you can turn on Rails rescuing on a # per-scenario basis, simply tagging it with @allow-rescue ActionController::Base.allow_rescue = false - -require 'webrat' -require 'webrat/core/matchers' - -Webrat.configure do |config| - config.mode = :rails - config.open_error_files = false # Set to true if you want error pages to pop up in the browser + +# Whether or not to run each scenario within a database transaction. +# +# If you leave this to true, you can turn off traqnsactions on a +# per-scenario basis, simply tagging it with @no-txn +Cucumber::Rails::World.use_transactional_fixtures = true + +# How to clean your database when transactions are turned off. See +# http://github.com/bmabey/database_cleaner for more info. +if defined?(ActiveRecord::Base) + begin + require 'database_cleaner' + DatabaseCleaner.strategy = :truncation + rescue LoadError => ignore_if_database_cleaner_not_present + end end - -require 'cucumber/rails/rspec' diff --git a/features/support/rails_generators_env.rb b/features/support/rails_generators_env.rb index 1ce3ea3..780a09d 100644 --- a/features/support/rails_generators_env.rb +++ b/features/support/rails_generators_env.rb @@ -52,6 +52,7 @@ def setup_active_project_folder project_name end World(CommonHelpers) + module Matchers def contain(expected) simple_matcher("contain #{expected.inspect}") do |given, matcher| @@ -62,4 +63,4 @@ def contain(expected) end end -World(Matchers) +World(Matchers) \ No newline at end of file diff --git a/lib/mundo_pepino.rb b/lib/mundo_pepino.rb index 9daf97b..f3019ef 100644 --- a/lib/mundo_pepino.rb +++ b/lib/mundo_pepino.rb @@ -1,5 +1,5 @@ $:.unshift(File.dirname(__FILE__)) unless -$:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) + $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'mundo_pepino/base' require 'mundo_pepino/implementations_api' diff --git a/lib/mundo_pepino/es_ES/definitions.rb b/lib/mundo_pepino/es_ES/definitions.rb index 33af4b5..90f70d0 100644 --- a/lib/mundo_pepino/es_ES/definitions.rb +++ b/lib/mundo_pepino/es_ES/definitions.rb @@ -70,6 +70,7 @@ end Cuando /^(?:que )?#{_pulso_} (?:en )?el bot[oó]n (.+)$/i do |boton| + #TODO features/es_ES/cuando-adjunto-el-fichero.feature:22 # Capybara is case sensitive click_button(boton.to_unquoted.to_translated) end @@ -101,7 +102,7 @@ end Cuando /^(?:que )?#{_relleno_} (?!#{_localizador_de_atributo_anidado_(false)})(.+) con (?:el valor )?['"](.+)["']$/i do |campo, valor| - find_field_and_do_with_webrat :fill_in, campo, :with => valor + find_field_and_do :fill_in, campo, :with => valor end Cuando /^(?:que )?#{_relleno_}(?: los(?: siguientes)? campos)?:$/i do |tabla| @@ -112,7 +113,7 @@ Cuando /^(?:que )?#{_relleno_} #{_localizador_de_atributo_anidado_} con (?:el valor )?['"](.+)["']$/i do |campo, modelo, nombre, valor| field_id = nested_field_id(last_mentioned, modelo, campo, nombre) - find_field_and_do_with_webrat :fill_in, field_id, :with => valor + find_field_and_do :fill_in, field_id, :with => valor end Cuando /^(?:que )?elijo (?:#{_como_}) ?(.+) ['"](.+)["']$/i do |campo, valor| @@ -124,31 +125,45 @@ end Cuando /^(?:que )?marco (?:#{_como_})? ?(.+)$/i do |campo| - find_field_and_do_with_webrat :check, campo + find_field_and_do :check, campo end Cuando /^(?:que )?desmarco (?:#{_como_})? ?(.+)$/i do |campo| - find_field_and_do_with_webrat :uncheck, campo + find_field_and_do :uncheck, campo end Cuando /^(?:que )?adjunto el fichero ['"](.*)["'] (?:a|en) (.*)$/ do |ruta, campo| - find_field_and_do_with_webrat :attach_file, campo, + find_field_and_do :attach_file, campo, {:path => ruta, :content_type => ruta.to_content_type} end Cuando /^(?:que )?selecciono ["']([^"']+?)["'](?: (?:en (?:el listado de )?|como )(?!#{_fecha_y_o_hora_})(.+))?$/i do |valor, campo| begin + # TODO + # Y selecciono "Hortalizas" en el listado de "Tipos de cultivo" # lib/mundo_pepino/es_ES/definitions.rb:139 + # En la página el label es -> "Tipo de cultivo" if campo - select valor, :from => campo.to_unquoted.to_translated # Vía label + select valor, :from => campo.to_unquoted.to_translated # Vía label else - select valor + # TODO capybara always need a :from + #features/es_ES/cuando-selecciono-en-listado.feature:4 # Scenario: Selecciono una opción de una lista (*select*) + # Y selecciono "Hortalizas" debo pasar un string vacio por como capybara construye el objeto locator en concreto + # el uso de un función s(string) que sanitiza strings + if defined?(Webrat) + select valor + else + select valor, :from => "" + end end - rescue Webrat::NotFoundError - begin - previous_exception = $! - select(valor, :from => convert_to_field(campo)) # Sin label - rescue - raise "#{previous_exception}\nand\n#{$!}" + rescue StandardError => e + if (defined?(Webrat) && e.is_a?(Webrat::NotFoundError)) || (defined?(Capybara) && e.is_a?(Capybara::ElementNotFound)) + begin + previous_exception = $! + # TODO added to_s to capybara pass the steps + select(valor, :from => convert_to_field(campo).to_s) # Sin label + rescue + raise "#{previous_exception}\nand\n#{$!}" + end end end end @@ -192,7 +207,7 @@ begin HTML::FullSanitizer.new.sanitize(response.body).send(shouldify(should)) =~ /#{Regexp.escape(text.to_unquoted.to_translated)}/m rescue Spec::Expectations::ExpectationNotMetError - webrat.save_and_open_page + defined?(Webrat) ? webrat.save_and_open_page : save_and_open_page raise end end @@ -211,6 +226,11 @@ Entonces /^(#{_veo_o_no_}) #{_la_etiqueta_} (["'].+?['"]|[^ ]+)(?:(?: con)? el (?:valor|texto) )?["']?([^"']+)?["']?$/ do |should, tag, value | lambda { + # TODO tag in upcase must not be used + # features/es_ES/veo-etiqueta-con-valor.feature:4 + tag = tag.downcase # Capybara is casesensitive + # For capybara page.should have_css(tag.to_unquoted, :text => /.*#{Regexp.escape(value.to_translated)}.*/i) + if value response.should have_tag(tag.to_unquoted, /.*#{Regexp.escape(value.to_translated)}.*/i) else @@ -232,7 +252,10 @@ Entonces /^(#{_veo_o_no_}) (?:un|el) enlace (?:al? |para )?(.+)?$/i do |should, pagina| lambda { - response.should have_tag('a[href=?]', pagina.to_unquoted.to_page) + # TODO + # In webrat response.should have_tag('a[href=?]', pagina.to_unquoted.to_page) + # For capybara page.should page.should have_css("a[href='#{pagina.to_unquoted.to_page}']") + response.should have_tag("a[href='#{pagina.to_unquoted.to_page}']") }.send(not_shouldify(should), raise_error) end @@ -242,12 +265,18 @@ end Entonces /^(#{_veo_o_no_}) marcad[ao] (?:la casilla|el checkbox)? ?(.+)$/ do |should, campo| - field_labeled(campo.to_unquoted).send shouldify(should), be_checked + # TODO + if defined?(Webrat) + field_labeled(campo.to_unquoted).send shouldify(should), be_checked + else + has_checked_field?(campo.to_unquoted).send shouldify(should), be_true + end end Entonces /^(#{_veo_o_no_}) (?:una|la) tabla (?:(["'].+?['"]|[^ ]+) )?con (?:el|los) (?:siguientes? )?(?:valore?s?|contenidos?):$/ do |should, table_id, valores| table_id = "##{table_id.to_unquoted}" if table_id shouldified = shouldify(should) + #TODO For capybara page instead response and have_css instead have_selector response.send shouldified, have_selector("table#{table_id}") if have_selector("table#{table_id} tbody").matches?(response) @@ -260,7 +289,7 @@ valores.raw[1..-1].each_with_index do |row, i| row.each_with_index do |cell, j| - response.send shouldified, + response.send shouldified, have_selector("table#{table_id} #{tbody} tr:nth-child(#{i+start_row})>td:nth-child(#{j+1})") { |td| td.inner_text.should =~ /#{cell == '.*' ? cell : Regexp.escape((cell||"").to_translated)}/ } @@ -280,10 +309,10 @@ with_tag('div') do with_tag "label", label with_tag "input[type='radio']" - end + end when "select", "textarea": field_labeled(label).element.name.should == type - else + else field_labeled(label).element.attributes['type'].to_s.should == type end end diff --git a/lib/mundo_pepino/implementations_api.rb b/lib/mundo_pepino/implementations_api.rb index 96950bd..6ae140a 100644 --- a/lib/mundo_pepino/implementations_api.rb +++ b/lib/mundo_pepino/implementations_api.rb @@ -129,6 +129,42 @@ def last_mentioned_should_have_child(field_raw, name) end children.detect {|c| c.id == child.id}.should_not be_nil end + + def find_field_and_do(action, raw_field, options = nil) + if defined?(Webrat) + # Webrat + find_field_and_do_with_webrat(action, raw_field, options) + else + # Capybara + find_field_and_do_with_capybara(action, raw_field, options) + end + end + + def find_field_and_do_with_capybara(action, raw_field, options = nil) + do_with_capybara action, raw_field.to_unquoted.to_translated, options # a pelo (localización vía labels) + rescue Capybara::ElementNotFound + field = convert_to_field(raw_field, last_mentioned_model) + begin + do_with_capybara action, field.to_s, options # campo traducido tal cual... + rescue Capybara::ElementNotFound + #TODO cucumber -p capybara_es_ES features/es_ES/tenemos-en-bbdd-registros.feature:50 # Scenario: dos campos has_many del mismo modelo + # se busca un campo "name" tenemos "for=session_name" y el texto del label es 'Name' capybara es casesensitive + raise $! if field.to_s.capitalize == field.to_s + do_with_capybara action, field.to_s.capitalize, options + end + end + + def do_with_capybara(action, field, options) + if options + if options[:path] # and options[:content_type] + self.send action, field, options[:path]#, options[:content_type] + else + self.send action, field, options + end + else + self.send action, field + end + end def find_field_and_do_with_webrat(action, raw_field, options = nil) do_with_webrat action, raw_field.to_unquoted.to_translated, options # a pelo (localización vía labels) @@ -210,7 +246,13 @@ def nested_field_id(parent_resource, nested_model, nested_field, nested_name) def nested_field_id_prefix(parent_resource, resource) preprefix = nested_field_prefix_prefix(parent_resource.mr_model, resource.class) - Nokogiri::HTML.parse(response.body).xpath( + if defined?(Webrat) + html = response.body + else + html = body + end + + Nokogiri::HTML.parse(html).xpath( "//input[@type='hidden' and @value=#{resource.id}]" ).each do |input| return "#{preprefix}_#{$1}_" if input.attributes['id'].to_s =~ /#{preprefix}_([0-9]+)_id/ @@ -220,8 +262,14 @@ def nested_field_id_prefix(parent_resource, resource) def new_nested_field_id(parent_resource, model, field) preprefix = nested_field_prefix_prefix(parent_resource.mr_model, model) (0..MAX_NESTED_RESOURCES).each do |index| - if Nokogiri::HTML.parse(response.body).css("##{preprefix}_#{index}_id").empty? - return "#{preprefix}_#{index}_#{field}" + if defined?(Webrat) + if Nokogiri::HTML.parse(response.body).css("##{preprefix}_#{index}_id").empty? + return "#{preprefix}_#{index}_#{field}" + end + else + if Nokogiri::HTML.parse(body).css("##{preprefix}_#{index}_id").empty? + return "#{preprefix}_#{index}_#{field}" + end end end # TODO: raise too many nested resources @@ -232,9 +280,17 @@ def nested_field_prefix_prefix(parent_model, child_model) end def should_or_not_contain_text(params) - response.send( - shouldify(params[:should]), - contain(params[:text].to_unquoted.to_translated.to_regexp)) + if defined?(Webrat) + response.send( + shouldify(params[:should]), + contain(params[:text].to_unquoted.to_translated.to_regexp)) + else + #TODO capybara README recommends have_content + page.send( + shouldify(params[:should]), + have_text(params[:text].to_unquoted.to_translated.to_regexp) + ) + end end end end