Learning Cucumber: Step Definitions Part 1 (The Setup)

So Cucumber's Gherkin language is awesome. We can very simply write out a feature with plain english. And one rule I've learned with cucumber the simpler the better. What's really cool about Cucumber is that you can run tests based off the features you have made in plain English! How do you do that? Well, you write code that backs up the plain english instructions Gherkin instructions.

When you run Cucumber, you run it "above" the features file by typing the word "cucumber." The features file will contain, when we're all done, a plain english Gherkin file denoted with the extension .feature. Then next to that you will have a folder labeled "step_definitions." Step definitions are the codes that give Gherkin features meaning to a computer. These will have a ".rb" extension are written in ruby. This all makes sense when you start to run each step in the terminal, so let's do just that. Create a folder and name it whatever you want. I created a folder called "blogger_demo." Inside that folder type "mkdir features" into your folder. Now simply type "cucumber."
 
This is exactly what we wanted. The features file has nothing in it, so Cucumber is reading that there are no scenarios and no steps to even run this command on. So, let's choose a site (I'm using TrekToday.com) and see what features it may have that we can use to run a small test. Trek Today is awesome for Trekkers like me and has a handy navigation bar that I could use to check out all kinds of cool stuff that isn't just Star Trek, but also CSI Files and other CBS television treasures. 

What I want to do is see if Trek Today's CSI Files button works. Now as a Cucumber newbie, I decided it is best to do a manual test to see what the button actually does. It takes us to another site, CSI Files, which is similar in format to Trek Today. So let's create a file called "navbar_buttons.feature" and write out our Gherkin. I should be able to press the CSI Files button on the navbar and be taken to the CSI Files site. In Gherkin that is said even more simply:



Now that this is written out in Gherkin the computer does have something it can read. However that doesn't mean that the computer is going to carry out instructions that you have. To understand this a little better type "cucumber" into your terminal.

So our computer has read our Gherkin file and determined that there are three steps: a given, when and then step. However, the computer can't do anything with that and therefore the tests are undefined. A lot of our work is cut out for us. If you copy from the Given all the way down to the last "end" statement and paste it into a ".rb" file, you have a lot of the coding work done for you. All we have to do is add the executable code into the file. However that is best explained in Part 2.

No comments:

Post a Comment