1
OK,這是我的RSpec代碼...的Ruby/Rails/Rspec的 - 的ActiveRecord :: AssociationTypeMismatch:
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=>#<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>
所以我們可以看到,收件人是一個用戶。
在控制器方面,我們看到有...
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 <top (required)>'
# ./spec/controllers/cards_controller_spec.rb:44:in `block (4 levels) in <top (required)>'
那麼......用戶對象如何以字符串形式更改爲其id?有任何想法嗎?
謝謝,這有幫助。我改變了我看起來像之前... 前(:每個)做 ATTR = {:問候=> 「Lorem存有」:recipient_id => recipient.id} 結束 那是你的意思?這擺脫了我所看到的錯誤,但現在... card = current_user.sent_cards.build(params [:card]) (card,attr和recipient_id應該在前面有「at」標誌)顯示創建的卡中的recipient_id爲零。在構建卡之前,我需要從recipient_id獲取用戶嗎?還有別的嗎? – slabounty 2011-12-22 06:36:54
想通了。不同的問題。必須使用find_by_id獲取收件人。 再次感謝。 – slabounty 2011-12-22 17:34:42