Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSam Berson
2,626 PointsTesting Friendships: "UserFriendship should belong to friend." Error (Rails 4)
The test at 4:55 which seems to pass in the video, fails for me. Here's the error I'm getting:
1) Failure:
UserFriendshipTest#test_: UserFriendship should belong to friend. [/Users/Sam/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/shoulda-context-1.2.1/lib/shoulda/context/context.rb:344]:
Expected UserFriendship to have a belongs_to association called friend (Friend does not exist)
My 'user_friendship_test.rb' file looks like this:
require 'test_helper'
class UserFriendshipTest < ActiveSupport::TestCase
should belong_to(:user)
should belong_to(:friend)
end
My 'user_friendship.rb' file looks like this:
class UserFriendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend
end
I should point out that I'm using Rails 4.
Any help would be much appreciated :)
4 Answers
Keith Gordon
429 Points@Sam Berson
use this code for user_friendship.rb
class UserFriendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, class_name: 'User', foreign_key: 'friend_id'
end
```
Naomi Freeman
Treehouse Guest TeacherI could be wrong, but in my Rails 4 app, I had to go in and define user_friendship inside the User model:
https://github.com/summerspirit/laughing-wookie/blob/master/app/models/user.rb
I don't remember if that's the thing that got the test to pass though. (or if my tests are passing at all at this point)
Sam Berson
2,626 PointsNope, that hasn't solved the problem - I think the issue is the fact that it's simply not detecting my 'friend' code in the 'user_friendship.rb' file. I'm not sure how to fix it though :(
Naomi Freeman
Treehouse Guest Teacherdid you generate a migration or just write the belongs_to in there?
Sam Berson
2,626 PointsYup, just tried 'rake db:migrate' and still getting the error :(
Sam Berson
2,626 PointsCan anyone help me out? Jason Seifer
Reid McGregor
6,846 PointsReid McGregor
6,846 PointsKeith's answer got this to pass for me.