SUPPORT THE SITE WITH A CLICK

Subscribe Rss:

SUPPORT THE SITE WITH A CLICK

Monday, September 5, 2011

Rspec views with Rails 3

For a long time, i didn't try with creating apps with BDD or TDD.So i decided to go with rspec, after reading the Rails Views from The Rspec Book.A view spec is a collection of code examples for a particular view template.View specs live in spec/views and render view templates in isolation.

Let's generate a fresh app with rails version 3.0.6, rspec 2.3.0 & rspec-rails 2.3.1.As we are using rspec, so remove the test folder from the rails project direcory.

If you type rails generate, the only RSpec generator you'll actually see is rspec:install. That's because RSpec is registered with Rails as the test framework, so whenever you generate application components like models, controllers, etc, RSpec specs are generated instead of Test::Unit tests.

First i have generated my model with title and description attributes for creating a simple form.
rails g model post title:string description:text

rake db:migrate

rake db:test:prepare

Second, i have generated my post controller with actions index, show, new, create, update and delete.

Lets we build a view that creates the post with title and description, and we will drive it out with spec.Now look into the directory /spec/views/posts/ add the following content into the file new.html.erb_spec.rb


Stub_model method generates an instance of a Active Model model.We use stub_model in any example (model, view, controller, helper), it is especially useful in view examples, which are inherently more state-based than interaction-based.

Now run the spec:

ruby -S bundle exec rspec spec/views/posts/new.html.erb_spec.rb.
Then you should see the spec fails.Let's do the changes in the views template views/posts/new.html.erb, posts controller and make the spec passes the test.


Once the post has been created, then we are moving to the show action.So lets write the spec for show


Now run the spec:

ruby -S bundle exec rspec spec/views/posts/show.html.erb_spec.rb.
Then you should see the spec fails.Let's do the changes in the views template views/posts/show.html.erb, posts controller and make the spec passes the test.

On clicking the edit link, we are moving to edit page and calling the edit action.