View Specs

When testing a view you want to stub the controller and render its view. In a before block, start by creating an instance of the controller that will render your view:

@controller = Posts.new(fake_request)
Posts being the name of my controller. fake_request is a helper (TODO: explain more)

Next we need to assign some values to pass to the view:

@controller.instance_variable_set(:@posts, [Post.new(:id => 1, :body => "Merb!")])

In this example we are creating a controller instance variable called @posts, it’s an array containing one instance of the Post object with 2 attributes set: id and body.

Finally, we can use the rspec matchers to make sure our views are ok.

describe "posts/index" do

  before( :each ) do
    @controller = Posts.new(fake_request)
    @controller.instance_variable_set(:@posts, [Post.new(:id => 1, :body => "Merb!")]) 
    @body = @controller.render(:index)
  end

  it "should have something" do
    @body.should have_tag(:div, :class => :posts).with_tag(:div, :class => :post)
  end

  it "should wrap the body paragraph in a div with class 'post' and the post's id" do
    @body.should have_tag(:div, :class => :post, :id => @post.id).with_tag(:p, :class => :body)
  end

  it "should render the body body within a post div" do
    @body.should have_tag(:div,:id => @post.id).with_tag(:p) {|p| p.should contain(@post.body)}
  end
end

look at the slapp demo app for more detailed example

Edit Page | History | Version: