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

Justin Ko jko170 at gmail.com
Sun Nov 20 02:58:41 EST 2011


On Nov 19, 2011, at 11:14 PM, Patrick J. Collins wrote:

>> Please post the backtrace.
> 
> Failures:
> 
>  1) PostsController#store_post_params stores the last post params in the session
>     Failure/Error: post :create, { :submit_action => submit_type.to_s, :post => { :foo => "bar" } }
>     ActiveRecord::UnknownAttributeError:
>       unknown attribute: foo
>     # ./app/controllers/posts_controller.rb:107:in `new'
>     # ./app/controllers/posts_controller.rb:107:in `exposed_for_session'
>     # ./app/controllers/posts_controller.rb:9
>     # ./app/controllers/posts_controller.rb:37:in `create'
>     # ./spec/controllers/post_spec.rb:6:in `do_post'
>     # ./spec/controllers/post_spec.rb:25
> 
> -------------
> 
> and exposed_for_session is:
> 
>  def exposed_for_session
>    Post.new(session.delete(:last_post_params)) if session[:last_post_params]
>  end
> 
> Like I said, I tried stubbing out the new class method on post by doing something like:
> 
> fake_post = stub('Post', :save => true)
> Post.stubs(:new).returns(fake_post)
> 
> But I still get that same failure.
> 
> Patrick J. Collins
> http://collinatorstudios.com
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

I haven't used ActiveRecord in quite awhile (been using MongoDB), but it looks like you cannot instantiate a record with attributes that don't exist. I think you have two options here:

1.) Only use valid attributes in your params.
2.) Add `with` to your stub to exactly match the arguments to `.new`:
      Post.stubs(:new).with({last_post_params: {foo: 'bar'}}).returns(fake_post)



More information about the rspec-users mailing list