OK, here's my rspec code ...
before(:each) do
@attr = { :greeting => "Lorem ipsum", :recipient => @recipient }
end
it "should redirect to the home page" do
puts "spec: @attr = #{@attr}"
puts "spec: recipient = #{@attr[:recipient]}"
post :create, :card => @attr
response.should redirect_to(root_path)
end
Now the output from this is:
spec: @attr = {:greeting=>"Lorem ipsum", :recipient=>#<User id: 2, first_name: "Example", last_name: "User", email: "[email protected]", created_at: "2011-12-22 04:01:02", updated_at: "2011-12-22 04:01:02", encrypted_password: "2d1323ad5eb21fb5ae5e87dfa78a63b521c56833189cc049ee2...", salt: "2679fcc29a30e939541cb98cb65d1d508035fea0eff1136037a...", admin: false>}
spec: recipient = #<User:0xac5d80c>
So we can see that recipient is a User.
On the controller side, we see have ...
def create
puts "create: Params = #{params}"
@card = current_user.sent_cards.build(params[:card])
if @card.save
flash[:success] = "Card created!"
redirect_to root_path
else
render 'pages/home'
end
end
With a display of ...
create: Params = {"card"=>{"greeting"=>"Lorem ipsum", "recipient"=>"2"}, "controller"=>"cards", "action"=>"create"}
and I see an error of ...
1) CardsController POST 'create' success should create a card
Failure/Error: post :create, :card => @attr
ActiveRecord::AssociationTypeMismatch:
User(#90303150) expected, got String(#76171330)
# ./app/controllers/cards_controller.rb:7:in `create'
# ./spec/controllers/cards_controller_spec.rb:47:in `block (5 levels) in <top (required)>'
# ./spec/controllers/cards_controller_spec.rb:44:in `block (4 levels) in <top (required)>'
So ... how did the User object get changed into its id as a string? Any ideas?
You cannot pass an entire object as a parameter. Rails replaces the object with its id if it has one or else passes a string representation of the object i.e. #<User:0xac5d80c>
for your case if it doesn't find the id.
So for your case, you should rename the :recipient parameter to :recipient_id. Then
@card = current_user.sent_cards.build(params[:card])
will create your card with the associated recipient as we have passed in the recipient_id.