I. Giới thiệu: Mình muốn chia sẻ đến với các bạn về cucumber. Trước khi vào bài, mình muốn nói một quy trình đơn giản khi xây dựng dự án như sau:
1. Viết test trước
2. Chạy test và thấy nó thất bại, khi đó bạn sẽ biết phải làm gì tiếp theo để qua test case
3. Cài đặt để vượt qua tất cả test
4. Chỉnh sửa, tối ưu code
Bắt đầu với một ví dụ nhỏ để bạn có thể làm quen dần với cú pháp, ta có một file feature như sau:
1# feature/hello_cucumber.feature
Feature: Hello Cucumber
As a product manager
I want our users to be greeted when they visit our site
So that they have a better experience
Scenario: User sees the welcome message
When I go to the homepage
Then I should see the welcome message
Khi viết các file feature các bạn có thể viết theo mẫu sau:
1Feature: <feature title>II. Steps và definition
As a <persona|role>
I want to <action>
So that <outcome>
Chúng ta đã có file feature, giờ bắt đầu viết những hướng dẫn kịch bản hay gọi là các bước (steps)
và chúng ta sẽ sử dụng chúng để thử nghiệm.
Cách hoạt động của nó là: đối với mỗi bước có trong kịch bản, chúng ta sẽ cung cấp một khối mã ruby để thực thi. Trong ví dụ này, chúng ta sẽ đặt các khối code (definition) trong một tệp có tên: hello_steps.rb:
1When(/^I go to the homepage$/) do visit root_pathChúng ta chỉ cần kết hợp mỗi dòng trong tập tin feature (được gọi là kịch bản) với định nghĩa bước tương ứng của nó, phù hợp với chuỗi được định nghĩa bằng biểu thức chính quy.
end
Then(/^I should see the welcome message$/) do expect(page).to have_content("Hello Cucumber")
end
Vì vậy, trong định nghĩa bước đầu tiên, chúng ta có "visit root_path" nghĩa là đi đển trang chủ (đó là một thuật ngữ rails mà chúng ta đã định nghĩa trong config/routes.rb). Bước tiếp theo sau đó là chúng ta sẽ kiểm tra xem trang web có chứa thông điệp "Hello Cucumber" không.
1# config/routes.rb
Rails.application.routes.draw do
root 'welcome#index'
end
# app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
def index
end
end
1# app/views/welcome/index.html.erb
<h1>Hello Cucumber</h1>
1$ cucumber -s
Using the default profile…
Feature: Hello Cucumber
Scenario: User sees the welcome message
When I go to the homepage
Then I should see the welcome message
1 scenario (1 passed)
2 steps (2 passed)
0m0.168s
Post A Comment:
0 comments: