Ruby / Rails / Rspec – ActiveRecord :: AssociationTypeMismatch:

好的,这是我的rspec代码……

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 

现在这个输出是:

 spec: @attr = {:greeting=>"Lorem ipsum", :recipient=>#} spec: recipient = # 

所以我们可以看到收件人是用户。

在控制器方面,我们看到……

 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 

随着…的显示

 create: Params = {"card"=>{"greeting"=>"Lorem ipsum", "recipient"=>"2"}, "controller"=>"cards", "action"=>"create"} 

我看到……的错误

 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 ' # ./spec/controllers/cards_controller_spec.rb:44:in `block (4 levels) in ' 

那么…… User对象是如何变成其字符串的id的呢? 有任何想法吗?

您不能将整个对象作为参数传递。 如果对象有一个id,则用它的id替换该对象,否则传递对象的字符串表示,如果它没有找到id, #

因此,对于您的情况,您应该将:recipient参数重命名为:recipient_id。 然后

 @card = current_user.sent_cards.build(params[:card]) 

我们已经在recipient_id中传递了相关收件人的卡片。