bdd cucumber_如何使用BDD構建堅如磐石的Ruby on Rails應用

bdd cucumber

by Marko Anastasov

通過Marko Anastasov

如何使用BDD構建堅如磐石的Ruby on Rails應用 (How to build rock-solid Ruby on Rails apps with BDD)

了解通過行為驅動開發來構建可持續Web應用程序的最佳實踐。 (Learn best practices for building sustainable web apps with behavior-driven development.)

Why do we fall sir? So that we can learn to pick ourselves up.

我們為什么要成為先生? 這樣我們就可以學會振作起來。

I built my first Rails app ten years ago. I’ve tried all approaches, and if there’s one thing that I’m certain of, it’s that I can’t work without writing tests. And writing tests first is what has helped me advance my programming skills the most.

十年前,我構建了我的第一個Rails應用程序。 我已經嘗試了所有方法,如果可以肯定的話,那就是沒有編寫測試我就無法工作。 首先編寫測試是幫助我最大程度地提高編程技能的原因。

It’s pretty simple. We want to feel and be as productive on day 1000 as we are on day 1 of the project. We want to be fast. For that we need clean code.

很簡單 我們希望在項目的第一天就感覺和在工作中一樣高效。 我們要快。 為此,我們需要干凈的代碼。

We can’t get everything right in the first pass, so we need to refactor. However, we can’t refactor under a constant fear that we’ll break stuff and ship bugs to production without knowing it. We need confidence that when we do break the code, we can detect and fix the issue right away.

我們不能在一開始就把所有事情都做好,所以我們需要重構。 但是,我們不能一直擔心會在不知不覺中破壞東西并將錯誤運送到生產環境中進行重構。 我們需要確信,當我們確實破壞代碼時,我們可以立即檢測并解決問題。

Where does confidence come from? The automated test suite gives us confidence. Confidence that we can change, remove, or add new code, and no major problem will happen as long as our tests are passing.

信心從何而來? 自動化測試套件使我們充滿信心。 我們可以更改,刪除或添加新代碼的信心,只要我們的測試通過,就不會發生重大問題。

So if tests are the foundation, let’s write them first. Do that for a while, and you’ll notice how clean and effective both your code and tests come out.

因此,如果測試是基礎,讓我們先編寫它們。 這樣做一會兒,您會注意到代碼和測試的效率和有效性。

了解“行為”觀點 (Understanding the “behavior” point of view)

When applying test-driven development (TDD), developers can easily fall into the trap of using unit tests to test what an object or method is, rather than what it does, which is a lot more useful.

當應用測試驅動開發(TDD),開發人員可以很容易地落入使用單元測試來測試的陷阱什么的對象或方法 ,而不是它什么,這是很多更加有用。

An example would be writing a test which asserts that a collection of comments is specifically an array, and not one of its unique features, such as being sorted by time. In most cases, it shouldn’t matter if we change the implementation of that collection to return a custom enumerable class. More generally:

一個示例就是編寫一個測試,該測試斷言一個注釋集合專門是一個數組,而不是其唯一功能之一,例如按時間排序。 在大多數情況下,是否更改該集合的實現以返回自定義可枚舉的類無關緊要。 更普遍:

Changing the implementation of an object shouldn’t break its test suite, as long as what the object does remains the same.
只要對象的行為保持不變,更改對象的實現就不應破壞其測試套件。

Behavior-driven development (BDD) puts focus on behavior — what a thing does — on all levels of development.

行為驅動的開發 (BDD)將注意力集中在所有級別的開發上的行為-一件事情做什么。

Initially, the word “behavior” may seem strange. Another way to frame this is to think about descriptions. We can describe every low-level method, object, button or screen to another person — and what we will be describing is exactly what a behavior is. Adopting this approach changes the way we approach writing code.

最初,“行為”一詞可能看起來很奇怪。 框架的另一種方式是考慮描述。 我們可以向另一個人描述每個低級方法,對象,按鈕或屏幕,而我們將要描述的正是行為。 采用這種方法會改變我們編寫代碼的方式。

“給定/何時/然后”通信模式 (The “Given / When / Then” communication pattern)

Most problems in software development are communication problems. For example, product manager fails to describe every use case of a proposed functionality. Developers misunderstand the scope of a feature. Product team doesn’t have a protocol to verify if a feature is done.

軟件開發中的大多數問題是通信問題。 例如,產品經理無法描述所提議功能的每個用例。 開發人員誤解了功能的范圍。 產品團隊沒有協議來驗證功能是否已完成。

BDD simplifies the language we use to describe scenarios in which software should be used:

BDD簡化了用于描述應使用軟件的方案的語言:

*Given* some context or state of the world,

*給出*一些背景或世界狀況,

*When* something happens,

* 當*發生某些事情時,

*Then* we expect some outcome.

* 然后*我們期待一些結果。

Given, When, Then are simple words we can use to describe a complex feature, code object, or a single method equally well. It’s a pattern that all members of the team in various roles can understand.

給定“何時”,“然后”是簡單的單詞,我們可以很好地描述復雜的功能,代碼對象或單個方法。 所有角色的團隊中的所有成員都可以理解這種模式。

These expressions are also built-in in many testing frameworks, such as Cucumber. A clear formulation of the problem and the solution that we need to implement helps us write better code.

這些表達式也內置在許多測試框架中,例如Cucumber 。 對問題和解決方案的清晰表述有助于我們編寫更好的代碼。

Rails的BDD工具概述 (Overview of BDD tools for Rails)

Ruby on Rails was the first web framework to ship with an integrated testing framework. This acted as a springboard for further advancements of the craft.

Ruby on Rails是第一個帶有集成測試框架的Web框架。 這充當了該技術進一步發展的跳板。

At the same time, the expressiveness of Ruby and the productivity boost in developing web applications with Rails attracted many experienced and high-profile engineers to the community early on.

同時,Ruby的表現力和使用Rails開發Web應用程序的工作效率提高,在早期就吸引了許多經驗豐富的知名工程師進入社區。

When you generate a new Rails application with default options, it sets the scene for testing using test/unit, a testing library that comes with Ruby. However, there are tools which make BDD easier to apply. I recommend using RSpec as the main testing library and Cucumber for writing high-level acceptance tests.

當您使用默認選項生成一個新的Rails應用程序時,它將使用Ruby附帶的測試庫test/unit設置要進行測試的場景。 但是,有些工具使BDD易于應用。 我建議使用RSpec作為主要測試庫,并建議使用Cucumber編寫高級驗收測試。

規范 (RSpec)

RSpec is a popular BDD testing library for Ruby. Tests written using RSpec — called specs — are executable examples of expected behavior of a piece of code in a specified context. This is much easier to understand by reading the following code:

RSpec是一個流行的Ruby BDD測試庫。 使用RSpec編寫的測試(稱為規范 )是在指定上下文中一段代碼的預期行為的可執行示例。 通過閱讀以下代碼,這將更容易理解:

describe ShoppingCart do  context "when first created" do    it "is empty" do      shopping_cart = ShoppingCart.new      expect(shopping_cart).to be_empty    end  endend

Well-written specs are easy to read, and as a result, understand. Try reading the code snippet above out loud. We are describing a shopping cart, saying that, given a blank context, when we create a new shopping cart, we expect(shopping_cart).to be_empty.

規范良好的規范易于閱讀,因此易于理解。 嘗試大聲閱讀上面的代碼片段。 我們正在描述一個購物車,說,給定空白上下文,當我們創建一個新的購物expect(shopping_cart).to be_empty ,我們expect(shopping_cart).to be_empty

Running this spec produces output which resembles a specification:

運行此規范將產生類似于規范的輸出:

ShoppingCart  when first created    is empty

We could use RSpec to specify an entire system, however we can also use a tool which helps us write and communicate even more naturally.

我們可以使用RSpec來指定整個系統,但是我們也可以使用一個工具來幫助我們更加自然地編寫和交流。

Cucumber (Cucumber)

As I explained in the first chapter of this guide, we want to test-drive the analysis phase of every new feature. To do that, we need customer acceptance tests to drive the development of the code which will actually implement the feature.

正如我在本指南第一章中所解釋的那樣,我們想測試每個新功能的分析階段。 為此,我們需要客戶驗收測試來驅動將實際實現該功能的代碼的開發。

If you are a developer working in a sufficiently complex organization, you may want to have somebody else, like a customer or product, manager write acceptance tests for you (disclaimer: I’ve never worked in such environment). In most cases, the developer writes them. This is a good practice, because it helps us understand better what it is that we need to build. Cucumber provides the language and format to do that.

如果您是在足夠復雜的組織中工作的開發人員,則可能希望讓其他人(例如客戶或產品),經理為您編寫驗收測試(免責聲明:我從未在這樣的環境中工作過)。 在大多數情況下,開發人員會編寫它們。 這是一個好習慣,因為它可以幫助我們更好地了解我們需要構建的內容。 Cucumber提供了這樣做的語言和格式。

Cucumber reads plain text descriptions of application features, organized in scenarios. Each step in the scenario is implemented using concrete code, and it automates interaction with your application from the user’s standpoint. For example:

Cucumber讀取按場景組織的應用程序功能的純文本描述。 該場景中的每個步驟都是使用具體代碼實現的,并且從用戶的角度來看,它可以自動與您的應用程序進行交互。 例如:

Feature: Reading articles
Scenario: Commenting on an article  Given I am logged in  And I am reading an article with "2" comments  When I reply to the last comment  Then the article should have "3" comments  And I should be subscribed to follow-up comments

If this were a web application, the scenario above could automatically boot a test instance of the application, open it a web browser, perform steps as any user would do, and then check if certain expectations have been met.

如果這是一個Web應用程序,則上述方案可以自動啟動該應用程序的測試實例,打開它的Web瀏覽器,像任何用戶一樣執行步驟,然后檢查是否滿足某些期望。

Rails中的BDD周期 (The BDD cycle in Rails)

In practice, BDD implies an outside-in approach. We start with an acceptance test, then write code in the views, and work our way down to the models. This approach helps us discover any new objects or variables we may need to effectively implement our feature early on, and make the right design decisions based on this.

在實踐中,BDD意味著從外而內的方法。 我們從驗收測試開始,然后在視圖中編寫代碼,然后逐步進行建模。 這種方法可幫助我們發現可能需要的任何新對象或變量,以盡早有效地實現我們的功能,并據此做出正確的設計決策。

The BDD cycle in Rails consists of the following steps:

Rails中的BDD周期包括以下步驟:

  1. Start with a new Cucumber scenario. Before you write it, make sure to analyze and understand the problem. At this point you need to know how the user interface allows a user to do a job. Do not worry about the implementation of scenario steps.

    從新的Cucumber方案開始 。 在編寫它之前,請確保分析并理解問題。 此時,您需要知道用戶界面如何允許用戶完成工作。 不必擔心方案步驟的實施。

  2. Run the scenario and watch it fail. This will tell you which steps are failing, or pending implementation. At first, most of your steps will be pending (undefined).

    運行該方案并觀察它是否失敗 。 這將告訴您哪些步驟失敗或正在執行。 首先,您的大多數步驟都將待處理(未定義)。

  3. Write a definition of the first failing or pending spec. Run the scenario and watch it fail.

    編寫第一個失敗或未決規范的定義 。 運行方案并觀察它是否失敗。

  4. Test-drive the implementation of a Rails view using the red-green-refactor cycle with RSpec. You’ll discover instance variables, controllers and controller actions that the view will need to do its job. This is also the only phase which has been proved to be optional in practice. An alternative approach is to simply prepare the views and controllers before moving on to the next step.

    使用帶有RSpec的紅綠色重構循環來測試Rails視圖的實現 。 您將發現視圖完成其工作所需的實例變量,控制器和控制器操作。 這也是實踐中被證明是可選的唯一階段。 另一種方法是簡單地準備視圖和控制器,然后再進行下一步。

  5. Test-drive the controller using the red-green-refactor cycle with RSpec. Make sure that the instance variables are assigned and that the actions respond correctly. The controllers are typically driven with a mocking approach. With the controller taken care of, you will know what the models or your domain objects should do.

    使用帶有RSpec的紅綠色重構循環對控制器進行試驅動 。 確保分配了實例變量,并且動作正確響應。 控制器通常通過模擬方法來驅動。 照顧好控制器后,您將知道模型或域對象應該做什么。

  6. Test-drive domain objects using the same red-green-refactor cycle with RSpec. Make sure that they provide the methods needed by the controller and the view. If you are working on a new feature for which a model does not exist yet, you should now generate the model and the corresponding database migrations. At this point you’ll know exactly what you need them to do.

    使用與RSpec相同的紅綠重構周期來測試驅動域對象 。 確保它們提供了控制器和視圖所需的方法。 如果您正在使用尚不存在模型的新功能,則現在應生成模型和相應的數據庫遷移。 此時,您將確切知道您需要他們做什么。

  7. Once you have implemented all the objects and methods you need and the corresponding specs are passing, run the Cucumber scenario you started with to make sure that the step is satisfied.

    一旦實現了所需的所有對象和方法,并且通過了相應的規范,請運行開始的Cucumber場景,以確保滿足該步驟

Once the first scenario step passes, move onto the next one and follow the same steps. Once your entire scenario has been implemented — the scenario is passing, along with all underlying specs — take a moment to reflect if there is something that you can refactor further.

一旦第一個方案步驟通過,請移至下一個方案并遵循相同的步驟。 實施完整個方案后(該方案以及所有基本規范都已通過),請花點時間思考是否可以進一步重構

Once you’re sure that you’ve completed the scenario, either move on to the next one, or show your work to others. If you work with a team, create a pull request or an equivalent request for a code review. Opening a pull request should automatically trigger a continuous integration build. When there are no more related scenarios left, show your work to your project manager or client, asking them to verify that you’ve built the right thing by deploying a feature branch to a staging server.

確定完成該方案后,要么繼續進行下一個,要么向他人展示您的工作。 如果您與團隊合作,請創建拉取請求或等效請求以進行代碼審查。 打開拉取請求應自動觸發持續集成構建。 如果沒有其他相關場景,請向項目經理或客戶展示您的工作,要求他們通過將功能分支部署到登臺服務器來驗證您是否構建了正確的東西。

This post is adapted from Rails Testing Handbook, a free ebook published by Semaphore. If you’ve made it this far and want to see some hands-on examples of writing behavior-driven code, download the book and let me know what you think of it. Thanks!

這篇文章改編自Semaphore出版的免費電子書《 Rails Testing Handbook》 。 如果到目前為止,您想要看一些動手編寫行為驅動代碼的示例,請下載本書,并告訴我您的想法。 謝謝!

翻譯自: https://www.freecodecamp.org/news/how-to-build-rock-solid-ruby-on-rails-apps-with-bdd-735de9319cc6/

bdd cucumber

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394400.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394400.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394400.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

go kegg_KEGG分析及可視化

上一篇推文中我們解釋了GO富集分析及可視化(GO富集分析及可視化),除了GO富集分析,我們經常在paper中看到KEGG分析,KEGG是什么呢,Kyoto Encyclopedia of Genes and Genomes,京都基因和基因組百科…

IntelliJ IDEA注冊碼

IntelliJ IDEA注冊碼 http://idea.lanyus.com/ 1.導航欄下 2.help下 3.register點擊 4.單選Activation code 5.粘貼注冊碼 轉載于:https://www.cnblogs.com/YUJIE666/p/10662561.html

單詞本.

offset 偏移量 charset字符集 str 代表String字符串 IgnoreCase忽略大小寫 Object 對象 argument 參數 if and only if:當且僅當 value:值 specified:指定 Parameters:參數 iterator:迭代器 invoke:調用 variable:變量 resolved:解決 sequnence 序列 default:默認轉載于:http…

leetcode931. 下降路徑最小和(動態規劃)

給定一個方形整數數組 A,我們想要得到通過 A 的下降路徑的最小和。 下降路徑可以從第一行中的任何元素開始,并從每一行中選擇一個元素。在下一行選擇的元素和當前行所選元素最多相隔一列。 示例: 輸入:[[1,2,3],[4,5,6],[7,8,9…

lvm使用

注:新添加的硬盤,如果沒有分區,可以直接使用pvcreate進行創建,然后用vgextend進行擴展如果新添加的硬盤經過分區,則要把需要擴展的分區修改為8e格式,則進行擴展以上內容實測~相關概念:pv:物理卷…

python django用戶登錄系統_Django實現用戶注冊登錄

學習Django中:試著著寫一個用戶注冊登錄系統,開始搞事情 O(∩_∩)O哈哈~Ubuntupython 2.7.12Django 1.10.4IDE:PycharmBootstrap(其實沒怎么用~~)新建項目:(我是直接用pycharm直接生成的)使用終端:(創建項目)django-ad…

ubantu 添加防火墻策略_ubuntu安裝防火墻并策略配置

1、安裝ubuntu防火墻sudo apt-get install ufw啟用sudo ufw enablesudo ufw default deny作用:開啟了防火墻并隨系統啟動同時關閉所有外部對本機的訪問(本機訪問外部正常)。關閉sudo ufw disable查看防火墻狀態sudo ufw status2、開啟/禁用相應端口或服務舉例sudo u…

如何使用React Native構建嵌套的抽屜菜單

by Dhruvdutt Jadhav由Dhruvdutt Jadhav 如何使用React Native構建嵌套的抽屜菜單 (How to build a nested drawer menu with React Native) Screen space is a precious commodity on mobile. The drawer menu (or “hamburger menu”) is one of the most popular navigatio…

c# WebApi之接口返回類型詳解

c# WebApi之接口返回類型詳解 https://blog.csdn.net/lwpoor123/article/details/78644998 轉載于:https://www.cnblogs.com/hwubin5/p/10665006.html

第十一次作業

1。題目&#xff1a; 輸入一個字符串&#xff0c;統計大寫字母、小寫字母、空格、數字和其他字符的個數。(要求用字符數組 代碼 #include<stdio.h> #define n 100 int main() {char a[n];int i,a10,b0,c0,d0;printf("輸入字符串&#xff1a;\n");gets(a);for(i…

Python Configparser模塊讀取、寫入配置文件

寫代碼中需要用到讀取配置&#xff0c;最近在寫python&#xff0c;記錄一下。 如下&#xff0c;假設有這樣的配置。 [db] db_host127.0.0.1 db_port3306 db_userroot db_pass [concurrent] thread200 processor400 可以使用ConfigParser模塊來讀取、寫入配置…

leetcode714. 買賣股票的最佳時機含手續費(動態規劃)

給定一個整數數組 prices&#xff0c;其中第 i 個元素代表了第 i 天的股票價格 &#xff1b;非負整數 fee 代表了交易股票的手續費用。 你可以無限次地完成交易&#xff0c;但是你每筆交易都需要付手續費。如果你已經購買了一個股票&#xff0c;在賣出它之前你就不能再繼續購買…

寧宛 機器人_全文閱讀 .007 忠犬機器人

全文閱讀 .007 忠犬機器人”其實光看i5高大的身軀、泛著金屬光澤的外殼&#xff0c;很難想象它能把照顧人的事情做的那么細致。這張同樣自帶程序的金屬床在i5的操作下&#xff0c;根據寧宛自身的體重及骨密度&#xff0c;調整出最適合她的硬度、角度及凹陷程度。空間跳躍……早…

servlet中文亂碼_10分鐘快速掌握Servlet相關基礎知識

Servlet的學習路線1、 創建Servlet2、 Servlet的相關配置3、 Servlet的生命周期4、 HttpServletRequest接口5、 HttpServletResponse接口6、 HttpSession接口7、 Filter、Listener接口Servlet的相關配置1、 創建Servlet extends HttpServlet2、 配置Serlvet第1種配置方式: web.…

蓋茨比喬布斯_如何使用蓋茨比創建您的博客并通過手機進行處理

蓋茨比喬布斯by Hu Chen胡Hu 如何使用蓋茨比創建您的博客并通過手機進行處理 (How to use Gatsby to create your blog and work on it from your phone) Recently, I decided to migrate my blog to Gatsby. Gatsby is a blazing fast static site generator based on React.…

python之collections之有序字典(OrderedDict)

一、定義OrderedDict是對字典的補充&#xff0c;它記住了字典元素的添加順序。eg&#xff1a; 二、OrderedDict相關方法def clear(self): # real signature unknown; restored from __doc__ """     od.clear() -> None. Remove all items from od. …

進階4:hive 安裝

安裝包&#xff1a; apache-hive-2.1.1-bin.tar.gz 安裝步驟&#xff1a; 1.上傳 apache-hive-2.1.1-bin.tar.gz 到linux; 2.解壓文件&#xff1a; tar zxvf apache-hive-2.1.1-bin.tar.gz 3.安裝mysql (僅支持mysql 5.7以下版本&#xff0c;不支持5.7或更高版本&#xff0c…

macbookpro接口叫什么_【科普】什么是雷電接口?蘋果電腦MACBOOK PRO有嗎?

剛接觸筆記本的朋友不知道USB-C口是什么,也不知道雷電接口(Thunderbolt)是什么,只知道MACBOOK PRO有雷電3接口。簡單來說 雷電接口是USB TYPE-C的替代模式,在此了解【什么是USB TYPE-C】 什么是雷電接口? 借用百度百科的表達 2011年2月24日,英特爾發布了長期以來廣為宣傳的…

GoldenGate 12.3微服務架構與傳統架構的區別

隨著Oracle GoldenGate 12c&#xff08;12.3.0.1.0&#xff09;的發布&#xff0c;引入了可用于復制業務數據的新架構。 多年來&#xff0c;這種架構有著不同的稱謂&#xff0c;Oracle終于在最后GA發布的版本中&#xff0c;以“Microservices”的名義確認新架構的名稱。Microse…

leetcode劍指 Offer 63. 股票的最大利潤(動態規劃)

假設把某股票的價格按照時間先后順序存儲在數組中&#xff0c;請問買賣該股票一次可能獲得的最大利潤是多少&#xff1f; 示例 1: 輸入: [7,1,5,3,6,4] 輸出: 5 解釋: 在第 2 天&#xff08;股票價格 1&#xff09;的時候買入&#xff0c;在第 5 天&#xff08;股票價格 6&…