[rspec-users] help with rspec'ing controller

Michael Klishin michael.s.klishin at gmail.com
Tue May 8 13:13:21 EDT 2007


On 08/05/07, Steve Odom <steve.odom at gmail.com> wrote:
> I'm not sure what you mean by prepair mock/stub completely. Can you provide
> a sample of how you would rspec a simple create action, such as:
>
> def create
>     @product = Product.new(params[:product])
>     if @product.save
>       flash[:notice] = 'Product was successfully created.'
>       redirect_to :action => 'list'
>     else
>       render :action => 'new'
>     end
>   end

I am still using 0.8.2 so:

specify "should save valid object and redirect to list of objects" do
	@model = mock("model")
	@model.should_receive(:save).and_return(true)
	
	post :create, { :product => @model }
	assigns[:product].should be_instance_of(Product) # not nil and
instance of right class
																									 # save call verified by mock object
	response.should be_redirect											 # redirect
	controller.should_redirect_to(:action => :list)  # redirected to :list
end

specify "should redirect to new object page if instance cannot be saved" do
	@model = mock("model")
	@model.should_receive(:save).and_return(false)
	
	post :create, { :product => @model }
	assigns[:product].should be_instance_of(Product) # not nil and
instance of right class
																									 # save call verified by mock object
	response.should be_redirect											 # redirect
	controller.should_redirect_to(:action => :new)   # redirected to :new
end

> I might be misunderstanding you, but I thought it was preferable to
> mock/stub all the ActiveRecord instances in your controller and only focus
> on the controller responsibilities.

Exactly. But no need to verify that your mock creates valid object :)
If I got the idea of last example right... It was what you trying to
do.

-- 
This was freedom. Losing all hope was freedom.

Chasing the beauty in programming:
www.ruby-lang.org | www.rubyonrails.org


More information about the rspec-users mailing list