Showing posts with label cucumber. Show all posts
Showing posts with label cucumber. Show all posts

May 10, 2009

Writing the Reader's Stories for the First BDD Blog Release

I continue with my plan to write user stories for my first release. In this post I'll cover features from the readers perspective.

  1. Must be able to Create, Edit and View posts.
  2. Must support per post permanent URLs
Here's the first draft of the readers browsing feature. We'll see where it evolves to in the future.

Feature: browsing
As a reader
I want to browse the site
So that I can read it's content


#
# scenarios that involve the reader navigating to the
# home page as the number of available posts vary
#
Scenario: 0 of 0
Given that 0 posts exist
When I go to the home page
Then I should be on the error page
And I should see "page not found"

Scenario: 1 of 1
Given that 1 post exists
When I go to the home page
Then I should be on post page 1
And I should not see a link to the next post
And I should not see a link to the previous post

Scenario: 2 of 2
Given that 2 posts exist
When I go to the home page
Then I should be on post page 2
And I should see a link to the previous post
And I should not see a link to the next post


#
# Scenarios that involve the reader navigating to a specific
# post; the first, middle and last. These primarily demonstrate
# the behavior of the navigation links to previous and next
# post pages
#
Scenario: 1 of 2
Given that 2 posts exist
When I go to post page 1
Then I should not see a link to the previous post
And I should see a lnk to the next post

Scenario: 2 of 3
Given that 3 posts exist
When I go to post page 2
Then I should see a link to the previous post
And I should see a link to the next post


#
# navigation to specific posts is done through post
# page permalinks. The permalinks are derived from
# the title of the post
#
Scenario: navigate to an non-existant post
Given that no posts have been created
When I go to the path /posts/get-rich-overnight
Then I should be on the error page
And I should see "page not found"
And I should see a link to the home page

Scenario: navigate to an existing post
Given that post 1 exists
And that post 1 has the title "Get Rich Overnight"
And that post 1 has the body lorem ispum
When I go to /posts/get-rich-overnight
Then I should see "Get Rich Overnight"
And I should see lorem ipsum

Writing User Stories for the First BDDBlog Release

In a previous post I shared the basics of my release plan, crude as it was. Next I'm going to create user stories for the entire first release once that's done I'll plan and execute regular weekly iterations to complete all the release stories. The one thing I'm going to do a bit different is that I'm going to rough out my user stories directly to cucumber features then I will maintain a list of uncompleted features that can be prioritized as I burn it down.

The first task at hand is to turn my first release's outline into Cucumber features. As I do this I'm not going to get overly concerned about the wording of my features. I expect that I'll be massaging them as I implement them.

With all that out of the way It's time to burn down the items on my release list and create some features. The first two items in the list is the most basic;

  1. Must be able to Create, Edit and View posts.
  2. Must support per post permanent URLs

Next I'll look at this from each type of users role; Reader, Author and Admin but I'm going to do that in seperate posts.

Apr 26, 2009

Some Progress On My BDD Blog Project

I finally got around to doing some more work on my BDD Blog project over the weekend. Up to this point I had mostly been just experimenting (here, here and here), but this time I decided I was going to try and write and implement a real scenario.

My goal though is not so much to implement code. Instead I'm still trying to learn how to write features and specs. I want to get to the point where I'm comfortable enough with Cucumber, Webrat and RSpec that I'm confident I can express all the features for a release without wasting my time.

So lets start with the feature I'm going to try and implement. The feature it self is very straight forward. It walks through the process used by an author when creating a new post.

Scenario: save a draft post
Given I am logged in as John Doe
And I am on the post creation page
And I have filled in the title with "Get Rich Overnight"
And I have filled in the body with "lorem ipsum"
When I click the "Create" button
Then I should be on the post index page
And I should see "Post successfully created"
And I should see "1 to 1 of 1 posts"
And there should only be 1 post listed
And the first post's title should be "Get Rich Overnight"
And the first post's author should be "John Doe"
And the first post's status should be "draft"

I've already played around with AuthLogic and demonstrated it's use but there's a minor change here. I'm no longer testing authentication so I needed to reduce the login process to a single given statement.
Given I am logged in as John Doe

The code I used to do that is pretty straight foward.
Given /^I am logged in as (.+)$/ do |login|
Given "I am the registered user #{login}"
visit path_to("the login page")
fill_in('Login', :with => login)
fill_in('Password', :with => "password")
click_button("Login")
end

The only thing even remotely interesting here is that I'm calling one of my previously defined 'Given' statements from within this one.

The next few statements are very straight forward and were implemented entirely in cucumber with the existing scaffold for the Post resource.
And I am on the post creation page
And I have filled in the title with "Get Rich Overnight"
And I have filled in the body with "lorem ipsum"
When I click the "Create" button
Then I should be on the post index page
And I should see "Post successfully created"
The next line in this scenario:
And I should see "1 to 1 of 1 posts"
I now realize didn't belong in this scenario (I'll refactor that out later) but since I learned something while implementing it I'm going to share.

Specifically, what I learned was this statement has no real purpose. I wanted to make sure that only the new post was present but all this really does it check to see if the "1 to 1 of 1 posts" text is present. It doesn't provide any real validation of the number of posts on the page. In the future I'll move this out to a new feature that's specifically written to test the pagination summary.

This line was not originally in my feature:
And there should only be 1 post listed
I added it when I realized my mistake with the previous line. This statement directly tests the number of posts on the page by counting the table rows in the post index table. It's implementation is very straight forward:
Then /^there should only be (\d+) posts? listed$/ do |count|
response.should have_tag("tr" , :count =>(count.to_i + 1))
end

The next three lines:
And the first post's title should be "Get Rich Overnight"
And the first post's author should be "John Doe"
And the first post's status should be "draft"

These lines were all very similar. They are simply looking to make sure that the contents of specific columns in the post index table have the correct information. This statement is implemented with the following code:
Then /^the (.+) post's (.+) should be "([^\"]*)"$/ do |index, column, text|
response.should have_selector("table>tr:nth-child(#{position_to(index) + 1})") do |tr|
tr.should have_selector("td[class=
'#{column}']") do |td|
td.should contain(text)
end
end
end
There's not much special there but it was my first attempt at really trying to use the CSS selector notation. Maybe after I'm more comfortable with it I'll devote a post to just that but for now I'll just explain this method.

In a nutshell it simply looks to make sure that nth row in the post index table has a td tag with a class matching the column name and that it's content matches the text passed in.

You may also notice I have a poorly named method called position_to in this method that simply turns the english words; first, second, third, etc... into the appropriate fixnum. Hopefully down the road I can find a library that does this but if not maybe I'll expand my approach into a full fledged gem.

This pretty much covered what I did with Cucumber and Webrat to fully implement this scenario but I did dip down into some view, controller and model specs to get the job done. I'll save that for another post.

Mar 31, 2009

Testing Rails Authlogic with Cucumber

In early rails projects I rolled my own authentication system, later I used restful-authentication. This time I'm going to try out AuthLogic which seems to be fairly popular, cleanly packaged and actively developed. I may walk through an AuthLogic installation in a future post but today I just want to make sure it can play nicely with cucumber.

First I wrote a fairly basic login scenario. You'll notice I stuck with the declarative style in writing this and I followed the advice provided in "The RSpec Book". I use direct model access to create the registered user in the 'Given' but then use simulated browser access to do the login and verify the actions success.

Scenario: successful login
Given I am the registered user John Doe
And I am on the login page
When I login with valid credentials
Then I should be on the account page
And I should see "Login successful!"


This left me with three steps to implement:

Given /^I am the registered user (.+)$/ do |login|
params = {
"login"=> login,
"password"=>"password",
"password_confirmation"=>"password"
}
@user = User.create(params)
end

When /^I login with valid credentials$/ do
fill_in('Login', :with => @user.login)
fill_in('Password', :with => "password")
click_button("Login")
end

Then /^I should be on ([^\"]*)$/ do |page_name|
response.request.path.should == path_to(page_name)
end

All fairly straight forward. I don't expect any problems using Cucumber with Authlogic.

Mar 25, 2009

Baby Step #2 with Rails, RSpec and Cucumber

In my previous post I took my first stab at Cucumber; first writing a failing Scenario, then getting it to pass, then writing a failing Spec and getting it to pass. The scenario in the previous post was overly simple, in fact I was able to complete it without writing any code at all. My goal this time is to continue my education with a slightly more realistic scenario.

One way to attack an application is in the same order it's used. In the case of a blog the author will need to add content before the site has any value, so that seems like a reasonable starting point.

# RAILS_ROOT/features/author_publish.feature
Feature: author publish
As an author
I want to publish a post
So that it can be read

Scenario: publish a post
Given I am on the post creation page
When I add a new post
Then I should see a page for the new post

The narrative for this feature was easy but deciding on how to approach the first scenario wasn't. In the end after browsing around the web and reading tons of material it was another post from Ben Maybe called "Imperative vs Declarative Scenarios in User Stories" that seemed to help me decide.

With that feature in place running cucumber:
./script/cucumber features/author_publish.feature

Produces the following:
Feature: author publish
As an author
I want to publish a post
So that it can be read

Scenario: publish a post # features/author_publish.feature:6
Given I am on the post creation page # features/step_definitions/webrat_steps.rb:6
Can't find mapping from "the post creation page" to a path. (RuntimeError)
/home/mgreenly/Projects/blog/features/support/paths.rb:11:in `/^I am on (.+)$/'
features/author_publish.feature:7:in `Given I am on the post creation page'
When I add a new post # features/author_publish.feature:8
Then I should see a page for the new post # features/author_publish.feature:9

1 scenario
1 failed step
2 undefined steps

You can implement step definitions for missing steps with these snippets:

When /^I add a new post$/ do
pending
end

Then /^I should see a page for the new post$/ do
pending
end

The problem here is cucumber doesn't know what to map the phrase 'the post creation page' to. This can be fixed by adding the following code to the navigation helper.
# RAILS_ROOT/features/support/paths.rb
def path_to(page_name)
case page_name

when /the homepage/
root_path

when /the post creation page/
post_path("new")

else
raise "Can't find mapping from \"#{page_name}\" to a path."
end
end

Now we run cucumber again:
./script/cucumber features/author_publish.feature

And it produces the following:
Feature: author publish
As an author
I want to publish a post
So that it can be read

Scenario: publish a post # features/author_publish.feature:6
Given I am on the post creation page # features/step_definitions/webrat_steps.rb:6
undefined method `post_path' for # (NoMethodError)
/home/mgreenly/Projects/blog/features/support/paths.rb:9:in `/^I am on (.+)$/'
features/author_publish.feature:7:in `Given I am on the post creation page'
When I add a new post # features/author_publish.feature:8
Then I should see a page for the new post # features/author_publish.feature:9

1 scenario
1 failed step
2 undefined steps

You can implement step definitions for missing steps with these snippets:

When /^I add a new post$/ do
pending
end

Then /^I should see a page for the new post$/ do
pending
end

Now it's complaining that it can't find a mapping for the Post resource. That makes sense since in my previous round I only created a controller. Instead of laboring through the process to create the Post model why not cheat and use the built in generator.
./script/generate rspec_scaffold -f Post title:string body:text

Obvious, going this route means I've broken my previously completed feature, so out of curiosity lets check it out.

Running cucumber on the original feature:
./script/cucumber features/reader_browse.feature

Produces the following:
Feature: browsing
As a reader
I want to browse the site
So that I can read it's content

Scenario: visit the homepage # features/reader_browse.feature:6
When I go to the homepage # features/step_definitions/webrat_steps.rb:10
Then I should see "Hello world!" # features/step_definitions/webrat_steps.rb:93
expected the following element's content to include "Hello world!":
Posts: index
Listing posts
Title
Body
New post
(Spec::Expectations::ExpectationNotMetError)
features/reader_browse.feature:8:in `Then I should see "Hello world!"'

1 scenario
1 failed step
1 passed step


Broken as expected. The problem is that the index page no longer has the "Hello world!" text on it. No problem we'll fix that later, for now lets keep going on the new feature.

When I run cucumber now:
./script/cucumber features/author_publish.feature

I get:
Feature: author publish
As an author
I want to publish a post
So that it can be read

Scenario: publish a post # features/author_publish.feature:6
Given I am on the post creation page # features/step_definitions/webrat_steps.rb:6
When I add a new post # features/author_publish.feature:8
Then I should see a page for the new post # features/author_publish.feature:9

1 scenario
2 undefined steps
1 passed step

You can implement step definitions for missing steps with these snippets:

When /^I add a new post$/ do
pending
end

Then /^I should see a page for the new post$/ do
pending
end

So now the it's obviously finding the 'the post creation page' but the remaining When/Then are still pending.

So now I add the following code:
# RAILS_ROOT/features/step_definitions/publish_steps
When /^I add a new post$/ do
fill_in "Title" , :with => "Some Title"
click_button "Create"
end


Then I run cucumber:
./script/cucumber features/author_publish.feature

And get the following:
Feature: author publish
As an author
I want to publish a post
So that it can be read

Scenario: publish a post # features/author_publish.feature:6
Given I am on the post creation page # features/step_definitions/webrat_steps.rb:6
When I add a new post # features/step_definitions/posts_steps.rb:1
Then I should see a page for the new post # features/author_publish.feature:9

1 scenario
1 undefined step
2 passed steps

You can implement step definitions for missing steps with these snippets:

Then /^I should see a page for the new post$/ do
pending
end

Now I just need to satisfy the 'Then'
# RAILS_ROOT/features/step_definitions/publish_steps
Then /^I should see a page for the new post$/ do
response.should contain("Post was successfully created")
end


Then I run cucumber and get the following:
Feature: author publish
As an author
I want to publish a post
So that it can be read

Scenario: publish a post # features/author_publish.feature:6
Given I am on the post creation page # features/step_definitions/webrat_steps.rb:6
When I add a new post # features/step_definitions/publish_steps.rb:1
Then I should see a page for the new post # features/step_definitions/publish_steps.rb:6

1 scenario
3 passed steps


Everything works, except the feature I broke, but I'll pick up there in the next post.

Mar 23, 2009

Baby Step #1 with Rails, RSpec and Cucumber

There are lots of resources on the web to help get started with RSpec and Cucumber but there's still a learning curve that I think only experience will overcome. So I decided just to dive in. I don't claim what I've done here is right, or even a good idea, but it's where I started.

My initial goal is just to walk through the 'outside in' red/green/refactor process of writing a feature then examples without spending to much time worrying if I selected the right story or if it's implemented it correctly.

This initial cycle is mostly about learning what the tools can do for me.

The simplest story that I can imagine goes like this:

as a reader I want to browse the site so that I can read it's content.


So with that story in hand It's time to write my first feature
 #  ./features/reader_browses.feature
Feature: browsing
As a reader
I want to browse the site
So that I can view it's content

Scenario: visit the homepage
When I go to the homepage
Then I should see "Hello world!"


Next I run Cucumber, 'rake features', and get the following....

 Feature: browsing
As a reader
I want to browse the site
So that I can view it's content

Scenario: visit the homepage # features/reader_browses.feature:6
When I go to the homepage # features/step_definitions/webrat_steps.rb:10
undefined method `root_path' for # (NoMethodError)
/home/mgreenly/Projects/blog/features/support/paths.rb:6:in `/^I go to (.+)$/'
features/reader_browses.feature:7:in `When I go to the homepage'
Then I should see "Hello world!" # features/step_definitions/webrat_steps.rb:93

1 scenario
1 failed step
1 skipped step
rake aborted!


So the first error I get is because we don't have a default route, so lets fix it by adding the following line in "./config/routes.rb"

map.root :controller => 'posts'


Then I run Cucumber again, "rake features", and get the following....

 Feature: browsing
As a reader
I want to browse the site
So that I can read it's content

Scenario: visit the homepage # features/reader_browse.feature:6
When I go to the homepage # features/step_definitions/webrat_steps.rb:10
uninitialized constant PostsController (NameError)
(eval):2:in `/^I go to (.+)$/'
features/reader_browse.feature:7:in `When I go to the homepage'
Then I should see "Hello world!" # features/step_definitions/webrat_steps.rb:93

1 scenario
1 failed step
1 skipped step
rake aborted!


So now it's telling me that the default route points to a PostsController and that controller doesn't exist. So lets create both the controller and it's rspec framework with the built in generator.

./script/generate rspec_controller posts


Now I'll run the spec, "rake spec", to see what I get
 ..

Finished in 0.045209 seconds

2 examples, 0 failures


It passes of course because the controller doesn't do anything and the spec doesn't make any requirements on it.

So lets see what Cucumber says now, "rake features"
 Feature: browsing
As a reader
I want to browse the site
So that I can view it's content

Scenario: visit the homepage # features/reader_browses.feature:6
When I go to the homepage # features/step_definitions/webrat_steps.rb:10
No action responded to index. Actions: (ActionController::UnknownAction)
/usr/local/stow/ruby-1.8.7-p72/lib/ruby/1.8/benchmark.rb:308:in `realtime'
(eval):2:in `/^I go to (.+)$/'
features/reader_browses.feature:7:in `When I go to the homepage'
Then I should see "Hello world!" # features/step_definitions/webrat_steps.rb:93

1 scenario
1 failed step
1 skipped step
rake aborted!


There's still an error but it's changed. Now it's complaining because the there's no 'index' action on the Posts controller. So lets drop back to the rspec example for the Posts controller and create a requirement for the index action. Remember first I want it to fail, then pass.

# in ./spec/controllers/posts_controller_spec.rb
describe "GET 'index'" do
it "should be successful" do
get 'index'
response.should be_success
end
end


So now when I run "rake spec" I get....

.F.

1)
ActionController::UnknownAction in 'PostsController GET 'index' should be successful'
No action responded to index. Actions:
./spec/controllers/posts_controller_spec.rb:12:

Finished in 0.052123 seconds

3 examples, 1 failure
rake aborted!


Now that the spec is failing we can try to satisfy it. To do that I just create an empty file at "app/views/posts/index.erb" and then rerun "rake spec"
 ...

Finished in 0.049891 seconds

3 examples, 0 failures


So now that the spec passes I run Cucumber again, "rake features", and get ....
 Feature: browsing
As a reader
I want to browse the site
So that I can view it's content

Scenario: visit the homepage # features/reader_browses.feature:6
When I go to the homepage # features/step_definitions/webrat_steps.rb:10
Then I should see "Hello world!" # features/step_definitions/webrat_steps.rb:93
Could not parse document (RuntimeError)
features/reader_browses.feature:8:in `Then I should see "Hello world!"'

1 scenario
1 failed step
1 passed step
rake aborted!



It's still failing but now it's upset because it can't find the "Hello world!" text on the index page. This is easy to fix, I just need to add the text to "app/views/posts/index.erb". Now I run "rake features".....

Feature: browsing
As a reader
I want to browse the site
So that I can view it's content

Scenario: visit the homepage # features/reader_browses.feature:6
When I go to the homepage # features/step_definitions/webrat_steps.rb:10
Then I should see "Hello world!" # features/step_definitions/webrat_steps.rb:93

1 scenario
2 passed steps

It passes. Just to make sure I didn't screw anything up I run "rake spec" on more time.
...
Finished in 0.049713 seconds
3 examples, 0 failures


That makes one successfull pass through an outside-in red/green/refactor cycle using Cucumber and Rspec with Rails.

Start a BDD Rails Project

I was starting a new rails project today that I plan on developing with Cucumber and RSpec. I quickly realized that even though there are tons of tutorials out there none seemed to really describe the process of initializing a new project. So here it is in a nutshell.

$ rails blog
$ cd blog
$ ./script/generate rspec
$ ./script/generate cucumber
$ rake db:migrate

At this point you should be able to do a 'rake', 'rake spec' or 'rake features' command and not get any errors.