[rspec-users] testing a post to a controller's create action

Justin Ko jko170 at gmail.com
Sat Nov 19 14:40:01 EST 2011


On Nov 19, 2011, at 9:57 AM, Patrick J. Collins wrote:

>>> I never see the debugger prompt..  Can anyone PLEASE tell me why this is not
>>> working?  In any other test, binding.pry or debugger interrupts the test flow
>>> and gives me access to the current scope of the debugger call.
>> 
>> Got any authentication in front of posts#create?
> 
> Yeah, that was the problem!  There was authentication in the
> ApplicationController and so I needed a skip_before_filter...
> 
> Ok..  Taking this a step forward, what I really am trying to do is write
> tests that isolate some methods that are called by before_filters in my
> controller.
> 
> So, lets say I have something like:
> 
> class PostsController < ApplicationController
> 
>  before_filter :store_params, :only => :create
> 
>  def create
>    ... create stuff
>  end
> 
>  def store_params
>    session[:post_params] = params[:post]
>  end
> 
> end
> 
> What I would like to do is totally isolate store_params...  So I'd do something
> like:
> 
> describe "#store_params" do
>  it "saves the post params for later" do
>    session[:post_params].should be_blank
> 
> 	 post :create, { :post => { :fake_param => "foobar" } }
> 
> 	 session[:post_params][:fake_param].should == "foobar"
>  end
> end

#store_params is not an "action", therefore I would make it private.

Since it is used only by the #create action, I would spec it as part of the #create spec:

describe '#create' do
  it 'stores the :post params' do
    post :create, { :post => { :fake_param => "foobar" } }
    session[:post_params][:fake_param].should == "foobar"
  end
end


> 
> ...  Ok this is all groovy, except my tests will fail because fake_param is not
> an attribute on Post, and when it actually gets to the create method it
> essentially be trying to do Post.create!(:fake_param => "foobar")...  So
> obviously I could choose to go about this differently and use a real post
> attribute-- but I am just curious if there is a way to isolate the testing of
> this method and make #create not even connected in any way?
> 
> I was thinking originally that I should be able to do (prior to the post create
> call):

You can, but you should mock Post.create!:

describe '#create' do
  it 'stores the :post params' do
    Post.should_receive(:create!).and_return(true)
    post :create, { :post => { :fake_param => "foobar" } }
    session[:post_params][:fake_param].should == "foobar"
  end
end

> 
> PostsController.any_instance.stubs(:create).returns true
> 
> But that doesn't seem to do anything...
> 
> 
> Patrick J. Collins
> http://collinatorstudios.com
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users



More information about the rspec-users mailing list