Создание местоположения.
В первой части мы создали приложение, в котором перечислены местоположения на английском и испанском языках.
В этой части мы создадим новое местоположение, показывающее проблемы локализации на этом пути. Помните, что мы используем Cucumber и BDD для запуска нашего приложения.
Давайте напишем сценарий о том, как мы это сделаем.
Scenario: Create a new location | |
Given I am on new location page | |
And I fill in «Name» with «Shiny location» | |
When I press «Create» | |
Then I should see «Shiny location» |
Сценарий довольно короткий и не содержит подробностей реализации. В настоящее время, когда мы запускаем Cucumber, он запускает все сценарии. Нам действительно не нужно этого делать, поскольку мы сосредоточены только на Create a new location scenario
« Create a new location scenario
. К счастью, легко сказать Cucumber сосредоточиться только на сценариях «в процессе». Над новым сценарием добавьте тег @wip
. (wip = работа в процессе)
Теперь это должно выглядеть так.
@wip | |
Scenario: Create a new location | |
Given I am on new location page | |
And I fill in «Name» with «Shiny location» | |
When I press «Create» | |
Then I should see «Shiny location» |
Отлично, теперь мы можем запустить Cucumber и просто сосредоточиться на текущем сценарии.
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/manage_locations.feature:20 | |
And I fill in «Name« with «Shiny location« # features/manage_locations.feature:21 | |
When I press «Create« # features/manage_locations.feature:22 | |
Then I should see «Shiny location« # features/step_definitions/location_steps.rb:9 | |
1 scenario (1 undefined) | |
4 steps (1 skipped, 3 undefined) | |
0m0.465s | |
You can implement step definitions for undefined steps with these snippets: | |
Given /^I am on new location page$/ do | |
pending # express the regexp above with the code you wish you had | |
end | |
Given /^I fill in «([^«]*)« with «([^«]*)«$/ do |arg1, arg2| | |
pending # express the regexp above with the code you wish you had | |
end | |
When /^I press «([^«]*)«$/ do |arg1| | |
pending # express the regexp above with the code you wish you had | |
end | |
The —wip switch was used, so the failures are expected. |
ПРОВАЛ! Как и ожидалось, Cucumber говорит нам, что у нас есть неопределенные сценарии. Давайте отбросим этот сценарий и сделаем его зеленым.
Скопируйте определения шагов для неопределенных шагов в файл features / step_definitions / location_step.rb .
Given /^I am on new location page$/ do | |
pending # express the regexp above with the code you wish you had | |
end | |
Given /^I fill in «([^»]*)» with «([^»]*)»$/ do |arg1, arg2| | |
pending # express the regexp above with the code you wish you had | |
end | |
When /^I press «([^»]*)»$/ do |arg1| | |
pending # express the regexp above with the code you wish you had | |
end |
Начиная с определения первого шага, мы посещаем new_location_path .
Given /^I am on new location page$/ do | |
visit(new_locations_path) | |
end |
Запуск сценария теперь дает следующий результат.
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
undefined local variable or method `new_location_path‘ for #<Cucumber::Rails::World:0x0000010332f330> (NameError) | |
./features/step_definitions/location_steps.rb:23:in `/^I am on new location page$/‘ | |
features/manage_locations.feature:20:in `Given I am on new location page‘ | |
And I fill in «Name» with «Shiny location» # features/step_definitions/location_steps.rb:26 | |
When I press «Create» # features/step_definitions/location_steps.rb:30 | |
Then I should see «Shiny location» # features/step_definitions/location_steps.rb:9 | |
Failing Scenarios: | |
cucumber -p wip features/manage_locations.feature:19 # Scenario: Create a new location | |
1 scenario (1 failed) | |
4 steps (1 failed, 3 skipped) | |
0m0.771s | |
The —wip switch was used, so the failures were expected. |
«Не определенная локальная переменная или метод« new_location_path »?» Говорит нам, что нам нужно добавить маршрут. Откройте файл route.rb в папке / config и добавьте новый маршрут.
match ‘locations/new’ => ‘locations#new’, :as => :new_locations |
Что происходит, когда мы запускаем тест?
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
The action ‘new‘ could not be found for LocationsController (AbstractController::ActionNotFound) | |
./features/step_definitions/location_steps.rb:23:in `/^I am on new location page$/‘ | |
features/manage_locations.feature:20:in `Given I am on new location page‘ | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create» # features/step_definitions/location_steps.rb:30 | |
Then I should see «Shiny location» # features/step_definitions/location_steps.rb:9 | |
Failing Scenarios: | |
cucumber -p wip features/manage_locations.feature:19 # Scenario: Create a new location | |
1 scenario (1 failed) | |
4 steps (1 failed, 3 skipped) | |
0m0.527s | |
The —wip switch was used, so the failures were expected. |
Конечно, действие «новый» не может быть найдено для LocationsController. Cucumber помогает нам в создании нашего Rails-приложения. Давайте добавим это в файл location_controller.rb в папке / app / controllers.
# GET /locations/new | |
# GET /locations/new.json | |
def new | |
@location = Location.new | |
respond_to do |format| | |
format.html # new.html.erb | |
format.json { render json: @location } | |
end | |
end |
Хорошо, огурец, расскажи нам, что происходит сейчас …
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
Missing template locations/new, application/new with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. Searched in: | |
* «/Users/john/Sites/zzz/app/views« | |
(ActionView::MissingTemplate) | |
/Users/john/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/benchmark.rb:295:in `realtime‘ | |
./app/controllers/locations_controller.rb:16:in `new‘ | |
./features/step_definitions/location_steps.rb:23:in `/^I am on new location page$/‘ | |
features/manage_locations.feature:20:in `Given I am on new location page‘ | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
Then I should see «Shiny location« # features/step_definitions/location_steps.rb:9 | |
Failing Scenarios: | |
cucumber -p wip features/manage_locations.feature:19 # Scenario: Create a new location | |
1 scenario (1 failed) | |
4 steps (1 failed, 3 skipped) | |
0m0.546s | |
The —wip switch was used, so the failures were expected. |
Еще один ожидаемый результат, нам нужно создать наш взгляд на действие. В папке / app / views / location создайте новый файл .html.erb. В этом мы создадим форму.
<%= form_for(@location) do |f| %> | |
<p> | |
<%= f.label :name %> | |
<%= f.text_field :name %> | |
</p> | |
<p> | |
<%= f.submit %> | |
</p> | |
<% end %> |
Если я знаю свои Rails и BDD, мы должны пройти через первый шаг.
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
TODO (Cucumber::Pending) | |
./features/step_definitions/location_steps.rb:27:in `/^I fill in «([^«]*)« with «([^«]*)«$/‘ | |
features/manage_locations.feature:21:in `And I fill in «Name» with «Shiny location»‘ | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
Then I should see «Shiny location« # features/step_definitions/location_steps.rb:9 | |
1 scenario (1 pending) | |
4 steps (2 skipped, 1 pending, 1 passed) | |
0m0.662s | |
The —wip switch was used, so the failures were expected. |
Да, первый шаг проходит. Время сосредоточиться на втором шаге. Код для выполнения этого шага звучит так же, как имя шага (спасибо, Капибара!)
Given /^I fill in «([^»]*)» with «([^»]*)»$/ do |field, value| | |
fill_in(field, :with => value) | |
end |
Можете ли вы угадать, что Огурец скажет нам делать дальше?
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
TODO (Cucumber::Pending) | |
./features/step_definitions/location_steps.rb:31:in `/^press «([^«]*)«$/’ | |
features/manage_locations.feature:22:in `When I press «Create«‘ | |
Then I should see «Shiny location» # features/step_definitions/location_steps.rb:9 | |
1 scenario (1 pending) | |
4 steps (1 skipped, 1 pending, 2 passed) | |
0m0.561s | |
The —wip switch was used, so the failures were expected. All is good. |
Теперь нам нужно нажать кнопку «Создать». Опять же, помощники Капибары — наш друг. В файле location_steps шаг «Когда я нажимаю» выглядит следующим образом:
When /^I press «([^»]*)»$/ do |button| | |
click_button(button) | |
end |
Давайте запустим тест.
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
Then I should see «Shiny location« # features/step_definitions/location_steps.rb:9 | |
expected there to be content «Shiny location« in «Zzz\n\nLocations\n\n« (RSpec::Expectations::ExpectationNotMetError) | |
./features/step_definitions/location_steps.rb:11:in `/^(?:|I )should see «([^«]*)«$/’ | |
features/manage_locations.feature:23:in `Then I should see «Shiny location«‘ | |
Failing Scenarios: | |
cucumber -p wip features/manage_locations.feature:19 # Scenario: Create a new location | |
1 scenario (1 failed) | |
4 steps (1 failed, 3 passed) | |
0m0.612s | |
The —wip switch was used, so the failures were expected. All is good. |
Мы ожидали увидеть контент «Блестящее место» в «ИнтернационализацияnnLocationsnn». Давайте посмотрим на это внимательно.
Почему это собирается / места? Это должно идти в / location / create. Это должно быть проблемой маршрутизации, поэтому откройте файл rout.rb и в пределах локали и добавьте:
match «locations» => ‘locations#create’, :as => :locations, :via => [:post] |
Мы можем проверить, что наши маршруты выглядят правильно, используя rake routes
:
$ rake routes | |
locations (/:locale)/locations(.:format) locations#index | |
new_locations (/:locale)/locations/new(.:format) locations#new | |
locations POST (/:locale)/locations(.:format) locations#create | |
root /(:locale)(.:format) locations#index |
Это выглядит правильно, поэтому давайте запустим сценарий.
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
Then I should see «Shiny location« # features/step_definitions/location_steps.rb:9 | |
expected there to be content «Shiny location« in «Zzz\n\nLocations\n\n« (RSpec::Expectations::ExpectationNotMetError) | |
./features/step_definitions/location_steps.rb:11:in `/^(?:|I )should see «([^«]*)«$/’ | |
features/manage_locations.feature:23:in `Then I should see «Shiny location«‘ | |
Failing Scenarios: | |
cucumber -p wip features/manage_locations.feature:19 # Scenario: Create a new location | |
1 scenario (1 failed) | |
4 steps (1 failed, 3 passed) | |
0m0.613s | |
The —wip switch was used, so the failures were expected. All is good. |
В самом деле? Та же ошибка? Давайте посмотрим назад на наши маршруты. Первый маршрут в файле — это действие index. То, как работают маршруты, побеждает первый матч. Поскольку оба маршрута имеют названия местоположений, действие index всегда побеждает. У нас есть два возможных решения. Переместите маршрут создания действия в начало или добавьте :via => get
к действию index.
Мне нравится последнее. Давайте сделаем маршрут действия индекса похожим на:
match ‘locations/’ => ‘locations#index’, :as => :locations, :via => [:get] |
Перепроверьте маршруты:
locations GET (/:locale)/locations(.:format) locations#index | |
new_locations (/:locale)/locations/new(.:format) locations#new | |
locations POST (/:locale)/locations(.:format) locations#create | |
root /(:locale)(.:format) locations#index |
ОК, только действия GET вызовут страницу индекса. Наш сценарий должен быть счастливым или, по крайней мере, больше не жаловаться на маршруты.
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
The action ‘create‘ could not be found for LocationsController (AbstractController::ActionNotFound) | |
(eval):2:in `click_button‘ | |
./features/step_definitions/location_steps.rb:31:in `/^I press «([^»]*)»$/‘ | |
features/manage_locations.feature:22:in `When I press «Create«‘ | |
Then I should see «Shiny location» # features/step_definitions/location_steps.rb:9 | |
Failing Scenarios: | |
cucumber -p wip features/manage_locations.feature:19 # Scenario: Create a new location | |
1 scenario (1 failed) | |
4 steps (1 failed, 1 skipped, 2 passed) | |
0m0.558s | |
The —wip switch was used, so the failures were expected. All is good. |
Конечно же, есть новая ошибка. The action 'create' could not be found for LocationsController
. Вы можете увидеть, как использование Cucumber для управления дизайном приложения на Rails может привести к хорошей повторяющейся последовательности создания маршрута, действия и представления для сценария.
Здесь мы забыли C часть CRUD. Откройте location_controller и добавьте метод создания.
# POST /locations | |
# POST /locations.json | |
def create | |
@location = Location.new(params[:location]) | |
respond_to do |format| | |
if @location.save | |
format.html { redirect_to @location, notice: ‘Location was successfully created.’ } | |
format.json { render json: @location, status: :created, location: @location } | |
else | |
format.html { render action: «new» } | |
format.json { render json: @location.errors, status: :unprocessable_entity } | |
end | |
end | |
end |
Давайте запустим тест.
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
undefined method `location_url‘ for #<LocationsController:0x00000100c24330> (NoMethodError) | |
./app/controllers/locations_controller.rb:29:in `block (2 levels) in create‘ | |
./app/controllers/locations_controller.rb:27:in `create‘ | |
(eval):2:in `click_button‘ | |
./features/step_definitions/location_steps.rb:31:in `/^I press «([^«]*)«$/’ | |
features/manage_locations.feature:22:in `When I press «Create«‘ | |
Then I should see «Shiny location» # features/step_definitions/location_steps.rb:9 | |
Failing Scenarios: | |
cucumber -p wip features/manage_locations.feature:19 # Scenario: Create a new location | |
1 scenario (1 failed) | |
4 steps (1 failed, 1 skipped, 2 passed) | |
0m0.652s | |
The —wip switch was used, so the failures were expected. All is good. |
Хм. В методе создания мы перенаправляем его на @locations. Нам нужно добавить маршрут для этого.
В файле route.rb добавьте:
match «locations/show/(:id)» => ‘locations#show’, :as => :location |
Это завершает сценарий?
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
The action ‘show‘ could not be found for LocationsController (AbstractController::ActionNotFound) | |
(eval):2:in `click_button‘ | |
./features/step_definitions/location_steps.rb:31:in `/^I press «([^»]*)»$/‘ | |
features/manage_locations.feature:22:in `When I press «Create«‘ | |
Then I should see «Shiny location» # features/step_definitions/location_steps.rb:9 | |
Failing Scenarios: | |
cucumber -p wip features/manage_locations.feature:19 # Scenario: Create a new location | |
1 scenario (1 failed) | |
4 steps (1 failed, 1 skipped, 2 passed) | |
0m0.653s | |
The —wip switch was used, so the failures were expected. All is good. |
Нет, похоже, нам нужно добавить действие шоу. Откройте файл location_controller.rb и добавьте:
# GET /locations/1 | |
# GET /locations/1.json | |
def show | |
@location = Location.find(params[:id]) | |
respond_to do |format| | |
format.html # show.html.erb | |
format.json { render json: @location } | |
end | |
end |
Я уверен, что это будет работать сейчас.
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
Missing template locations/show, application/show with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. Searched in: | |
* «/Users/john/Sites/zzz/app/views« | |
(ActionView::MissingTemplate) | |
/Users/john/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/benchmark.rb:295:in `realtime‘ | |
./app/controllers/locations_controller.rb:43:in `show‘ | |
(eval):2:in `click_button‘ | |
./features/step_definitions/location_steps.rb:31:in `/^I press «([^»]*)»$/‘ | |
features/manage_locations.feature:22:in `When I press «Create«‘ | |
Then I should see «Shiny location» # features/step_definitions/location_steps.rb:9 | |
Failing Scenarios: | |
cucumber -p wip features/manage_locations.feature:19 # Scenario: Create a new location | |
1 scenario (1 failed) | |
4 steps (1 failed, 1 skipped, 2 passed) | |
0m0.613s | |
The —wip switch was used, so the failures were expected. All is good. |
К сожалению, нам нужно добавить файл show.html.erb. Создайте его в папке / app / views / location и добавьте код для отображения местоположения.
<p><%= @location.name %></p> |
Да, это не очень интересно, но мы просто сдаем тесты.
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
Then I should see «Shiny location« # features/step_definitions/location_steps.rb:9 | |
1 scenario (1 passed) | |
4 steps (4 passed) | |
0m0.585s | |
The —wip switch was used, so I didn‘t expect anything to pass. These scenarios passed: | |
(::) passed scenarios (::) | |
features/manage_locations.feature:19:in `Scenario: Create a new location‘ |
ВСЕ ЗЕЛЕНЫЕ!
Готовы к перерыву?
La Creación de Nuevas Ubicaciones
Сценарий с английским (по умолчанию) языком проходит, сейчас самое время сосредоточиться на испанском. Создайте новый сценарий в /features/manage_locations.feature.
@wip | |
Scenario: Create a new location | |
Given I am on the es site | |
And I am on new location page | |
And I fill in «Nombre» with «Shiny location» | |
When I press «crear» | |
Then I should see «Shiny location» |
Бьюсь об заклад, вы можете догадаться, какой будет результат этого сценария …
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
Then I should see «Shiny location« # features/step_definitions/location_steps.rb:9 | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:25 | |
Given I am on the es site # features/step_definitions/location_steps.rb:17 | |
And I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Nombre« with «buena ubicación« # features/step_definitions/location_steps.rb:26 | |
cannot fill in, no text field, text area or password field with id, name, or label ‘Nombre‘ found (Capybara::ElementNotFound) | |
(eval):2:in `fill_in‘ | |
./features/step_definitions/location_steps.rb:27:in `/^I fill in «([^»]*)» with «([^»]*)»$/‘ | |
features/manage_locations.feature:28:in `And I fill in «Nombre« with «buena ubicación«‘ | |
When I press «crear» # features/step_definitions/location_steps.rb:30 | |
Then I should see «buena ubicación» # features/step_definitions/location_steps.rb:9 | |
Failing Scenarios: | |
cucumber -p wip features/manage_locations.feature:25 # Scenario: Create a new location | |
2 scenarios (1 failed, 1 passed) | |
9 steps (1 failed, 2 skipped, 6 passed) | |
0m1.319s | |
The —wip switch was used, so I didn‘t expect anything to pass. These scenarios passed: | |
(::) passed scenarios (::) | |
features/manage_locations.feature:19:in `Scenario: Create a new location‘ |
Первые два шага одинаковы, поэтому они проходят с летающими цветами. Однако, наши виджеты теперь названы для локали, которую мы используем (и), и Cucumber не может найти. Помните I18n.translate? Мы снова используем это для поля имени. Откройте файл new.html.erb в папке представлений.
<%= form_for(@location) do |f| %> | |
<p> | |
<%= f.label :name, t(‘.name_html’) %> | |
<%= f.text_field :name %> | |
</p> | |
<p> | |
<%= f.submit %> | |
</p> | |
<% end %> |
Если мы сейчас запустим тест, оба сценария @wip потерпят неудачу, так как мы вызываем функцию перевода и мы не предоставили переводы. Давайте добавим их сейчас.
В папке / config / locales откройте файл en.yml и добавьте:
en: | |
locations: | |
index: | |
title_html: «Locations« | |
new: | |
name_html: «Name« |
Не забывайте испанский. Откройте файл es.yml и добавьте:
es: | |
locations: | |
index: | |
title_html: «Locaciones« | |
new: | |
name_html: «Nombre« |
Бьюсь об заклад, он может найти поле имени в обоих случаях сейчас.
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
Then I should see «Shiny location« # features/step_definitions/location_steps.rb:9 | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:25 | |
Given I am on the es site # features/step_definitions/location_steps.rb:17 | |
And I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Nombre« with «buena ubicación« # features/step_definitions/location_steps.rb:26 | |
When I press «crear« # features/step_definitions/location_steps.rb:30 | |
no button with value or id or text ‘crear‘ found (Capybara::ElementNotFound) | |
(eval):2:in `click_button‘ | |
./features/step_definitions/location_steps.rb:31:in `/^I press «([^»]*)»$/‘ | |
features/manage_locations.feature:29:in `When I press «crear«‘ | |
Then I should see «buena ubicación» # features/step_definitions/location_steps.rb:9 | |
Failing Scenarios: | |
cucumber -p wip features/manage_locations.feature:25 # Scenario: Create a new location | |
2 scenarios (1 failed, 1 passed) | |
9 steps (1 failed, 1 skipped, 7 passed) | |
0m0.648s | |
The —wip switch was used, so I didn‘t expect anything to pass. These scenarios passed: | |
(::) passed scenarios (::) | |
features/manage_locations.feature:19:in `Scenario: Create a new location‘ |
Похоже, нам нужно сделать то же самое для кнопки создания. На странице new.html.erb мы изменим кнопку отправки.
<p> | |
<%= f.button t(‘.button_html’) %> | |
</p> |
Конечно, мы должны добавить button_html в локали.
файл en.yml:
en: | |
locations: | |
index: | |
title_html: «Locations« | |
new: | |
name_html: «Name« | |
button_html: «Create« |
файл es.yml:
es: | |
locations: | |
index: | |
title_html: «Locaciones« | |
new: | |
name_html: «Nombre« | |
button_html: «crear« |
Мы все?
$ cucumber —profile wip | |
Using the wip profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
Then I should see «Shiny location« # features/step_definitions/location_steps.rb:9 | |
@wip | |
Scenario: Create a new location # features/manage_locations.feature:25 | |
Given I am on the es site # features/step_definitions/location_steps.rb:17 | |
And I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Nombre« with «buena ubicación« # features/step_definitions/location_steps.rb:26 | |
When I press «crear« # features/step_definitions/location_steps.rb:30 | |
Then I should see «buena ubicación« # features/step_definitions/location_steps.rb:9 | |
2 scenarios (2 passed) | |
9 steps (9 passed) | |
0m0.689s | |
The —wip switch was used, so I didn‘t expect anything to pass. These scenarios passed: | |
(::) passed scenarios (::) | |
features/manage_locations.feature:19:in `Scenario: Create a new location‘ | |
features/manage_locations.feature:25:in `Scenario: Create a new location‘ |
Ура! Однако, прежде чем мы отпразднуем, у нас есть пара дел. Удалите теги @wip
из файла объектов и повторно запустите сценарии.
$ cucumber | |
Using the default profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
Scenario: List a location. # features/manage_locations.feature:6 | |
Given there is a location named «location 1« # features/step_definitions/location_steps.rb:1 | |
When I am on the locations page # features/step_definitions/location_steps.rb:5 | |
Then I should see «Locations« # features/step_definitions/location_steps.rb:9 | |
And I should see «location 1« # features/step_definitions/location_steps.rb:9 | |
Scenario: List a location. # features/manage_locations.feature:12 | |
Given there is a location named «location 1« # features/step_definitions/location_steps.rb:1 | |
And I am on the es site # features/step_definitions/location_steps.rb:17 | |
When I am on the locations page # features/step_definitions/location_steps.rb:5 | |
Then I should see «Locaciones« # features/step_definitions/location_steps.rb:9 | |
And I should see «location 1« # features/step_definitions/location_steps.rb:9 | |
Scenario: Create a new location # features/manage_locations.feature:19 | |
Given I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
cannot fill in, no text field, text area or password field with id, name, or label ‘Name‘ found (Capybara::ElementNotFound) | |
(eval):2:in `fill_in‘ | |
./features/step_definitions/location_steps.rb:27:in `/^I fill in «([^»]*)» with «([^»]*)»$/‘ | |
features/manage_locations.feature:21:in `And I fill in «Name« with «Shiny location«‘ | |
When I press «Create» # features/step_definitions/location_steps.rb:30 | |
Then I should see «Shiny location» # features/step_definitions/location_steps.rb:9 | |
Scenario: Create a new location # features/manage_locations.feature:25 | |
Given I am on the es site # features/step_definitions/location_steps.rb:17 | |
And I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Nombre» with «buena ubicación» # features/step_definitions/location_steps.rb:26 | |
When I press «crear» # features/step_definitions/location_steps.rb:30 | |
Then I should see «buena ubicación» # features/step_definitions/location_steps.rb:9 | |
Failing Scenarios: | |
cucumber features/manage_locations.feature:19 # Scenario: Create a new location | |
4 scenarios (1 failed, 3 passed) | |
18 steps (1 failed, 2 skipped, 15 passed) | |
0m0.707s |
Какая?? В третьем сценарии он думает, что локаль — это es
поскольку это то, что мы установили во втором сценарии. В английских сценариях нам нужно добавить локаль в сценарии.
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
Scenario: List a location. | |
Given there is a location named «location 1» | |
And I am on the en site | |
When I am on the locations page | |
Then I should see «Locations» | |
And I should see «location 1» | |
Scenario: List a location. | |
Given there is a location named «location 1» | |
And I am on the es site | |
When I am on the locations page | |
Then I should see «Locaciones» | |
And I should see «location 1» | |
Scenario: Create a new location | |
Given I am on the en site | |
And I am on new location page | |
And I fill in «Name» with «Shiny location» | |
When I press «Create» | |
Then I should see «Shiny location» | |
Scenario: Create a new location | |
Given I am on the es site | |
And I am on new location page | |
And I fill in «Nombre» with «buena ubicación» | |
When I press «crear» | |
Then I should see «buena ubicación» |
Скрещенные пальцы…
$ cucumber | |
Using the default profile… | |
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
Scenario: List a location. # features/manage_locations.feature:6 | |
Given there is a location named «location 1« # features/step_definitions/location_steps.rb:1 | |
And I am on the en site # features/step_definitions/location_steps.rb:17 | |
When I am on the locations page # features/step_definitions/location_steps.rb:5 | |
Then I should see «Locations« # features/step_definitions/location_steps.rb:9 | |
And I should see «location 1« # features/step_definitions/location_steps.rb:9 | |
Scenario: List a location. # features/manage_locations.feature:13 | |
Given there is a location named «location 1« # features/step_definitions/location_steps.rb:1 | |
And I am on the es site # features/step_definitions/location_steps.rb:17 | |
When I am on the locations page # features/step_definitions/location_steps.rb:5 | |
Then I should see «Locaciones« # features/step_definitions/location_steps.rb:9 | |
And I should see «location 1« # features/step_definitions/location_steps.rb:9 | |
Scenario: Create a new location # features/manage_locations.feature:20 | |
Given I am on the en site # features/step_definitions/location_steps.rb:17 | |
And I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Name« with «Shiny location« # features/step_definitions/location_steps.rb:26 | |
When I press «Create« # features/step_definitions/location_steps.rb:30 | |
Then I should see «Shiny location« # features/step_definitions/location_steps.rb:9 | |
Scenario: Create a new location # features/manage_locations.feature:27 | |
Given I am on the es site # features/step_definitions/location_steps.rb:17 | |
And I am on new location page # features/step_definitions/location_steps.rb:22 | |
And I fill in «Nombre« with «buena ubicación« # features/step_definitions/location_steps.rb:26 | |
When I press «crear« # features/step_definitions/location_steps.rb:30 | |
Then I should see «buena ubicación« # features/step_definitions/location_steps.rb:9 | |
4 scenarios (4 passed) | |
20 steps (20 passed) | |
0m0.841s |
Excelente! Тодос сын Вердес.
В следующей части этой серии мы будем редактировать локации.
ДОПОЛНИТЕЛЬНЫЙ КРЕДИТ:
Контуры сценария.
Вы могли заметить, что первый и второй сценарии были практически идентичны. То же самое верно для третьего и четвертого сценариев. Мы можем сгруппировать их вместе с очертаниями.
Мы помещаем заполнитель в схему и соответствующие значения в таблице.
Feature: Manage locations | |
In order to manage locations | |
As a user | |
I want to create and edit my locations. | |
Scenario Outline: List locations | |
Given there is a location named «<location>» | |
And I am on the <language> site | |
When I am on the locations page | |
Then I should see «<title>» | |
And I should see «<result>» | |
Examples: | |
| location | language | title | result | | |
| location 1 | en | Locations | location 1 | | |
| location 2 | es | Locaciones | location 2 | | |
Scenario Outline:: Create a new location | |
Given I am on the <language> site | |
And I am on new location page | |
And I fill in «<name>» with «<location>» | |
When I press «<button>» | |
Then I should see «<result>» | |
Examples: | |
| language | name | location | button | result | | |
| en | Name | location 1 | Create | location 1 | | |
| es | Nombre | location 1 | crear | location 1 | |
Прелесть этого в том, что если вы хотите добавить тест, например, для проверки имени, мы можем легко добавить его в Примеры, как я сделал ниже:
Examples: | |
| language | name | location | button | result | | |
| en | Name | location 1 | Create | location 1 | | |
| es | Nombre | location 1 | crear | location 1 | | |
| en | Name | | Create | Name cannon be blank | |
Увидимся в следующий раз. Hasta Luego!