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

David Chelimsky dchelimsky at gmail.com
Sun Nov 20 07:41:21 EST 2011


On Nov 20, 2011, at 2:46 AM, Patrick J. Collins wrote:

>> 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)
> 
> Yeah..  I originally had tried your 2nd option...  Putting an expectation on
> the arguments sent to new made no difference.  I just tried it again to verify,
> and I still get the same error.  Seems so weird to me.

Then use the first! The potential problem is that the params change and you need to change them here, but you can alleviate that with a method like valid_attributes:

describe PostsController do
  def valid_attributes
    { :title => "Isolating change" }
  end

  describe "#store_params" do
    it "saves the post params for later" do
      session[:post_params].should be_blank
      post :create, { :post => valid_attributes }
      session[:post_params].should eq(valid_attributes)
   end
  end
end

You could also use FactoryGirl.attributes_for(:post) if you're using that tool. Either way, this removes the need to figure out where to stub what on the model. If you're concerned about the DB call, you could still stub save! but using valid_attributes would get you past the validations that happen before save!.

HTH,
David


More information about the rspec-users mailing list