Skip to content

Instantly share code, notes, and snippets.

@jasonm
Created August 20, 2009 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonm/171142 to your computer and use it in GitHub Desktop.
Save jasonm/171142 to your computer and use it in GitHub Desktop.
# Implementation
class PostsController < ApplicationController
def index
@posts = Post.published
end
def new
@post = Post.new
end
def create
@post = Post.new(params[:post])
@post.save
flash[:success] = 'Post created.'
redirect_to posts_path
end
end
# Functional (component) test
require 'test_helper'
class PostsControllerTest < ActionController::TestCase
context 'GET to index' do
setup do
Factory(:unpublished_post)
@published_posts = [Factory(:published_post), Factory(:published_post)]
get :index
end
should_render_template :index
should_respond_with :success
should_assign_to :posts
should "find all the published posts" do
assert_equal @published_posts, assigns(:posts)
end
end
context 'POST to create with valid parameters' do
setup do
@posts_count = Post.count
@post_attributes = Factory.attributes_for(:post)
post :create, :post => @post_attributes
end
should_set_the_flash_to /created/i
should_redirect_to('posts index') { posts_path }
should "create a post" do
assert_equal @posts_count + 1, Post.count
end
should "create a Post with the specified attributes" do
created_post = Post.last
@post_attributes.each do |attribute, value|
assert_equal value, created_post[attribute]
end
end
end
end
# Isolation test
require 'test_helper'
class PostsControllerTest < ActionController::TestCase
context 'GET to index' do
setup do
@published_posts = [Factory.stub(:post)]
Post.stubs(:published).returns(@published_posts)
get :index
end
should_render_template :index
should_respond_with :success
should_assign_to :posts
should "find all the published posts" do
assert_received(Post, :published)
end
should "pass the published posts into the view" do
assert_equal @published_posts, assigns(:posts)
end
end
context 'POST to create with valid parameters' do
setup do
@post_attributes = {}
@post = stub('post', :save => true)
Post.stubs(:new).returns(@post)
post :create, :post => @post_attributes
end
should_set_the_flash_to /created/i
should_redirect_to('posts index') { posts_path }
should "instantiate a Post with the specified attributes" do
assert_received(Post, :new) { |expect| expect.with(@post_attributes) }
end
should "save the Post" do
assert_received(@post, :save)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment