【问题标题】:Testing Friendships: "UserFriendship should belong to friend." Error (Rails 4)测试友谊:“用户友谊应该属于朋友。”错误(Rails 4)
【发布时间】:2014-05-13 17:00:27
【问题描述】:

我正在学习 Treehouse 课程,但在那里的论坛上没有得到积极的回应。这是我遇到的问题:

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)

我的“user_friendship_test.rb”文件如下所示:

require 'test_helper'

class UserFriendshipTest < ActiveSupport::TestCase
  should belong_to(:user)
  should belong_to(:friend)
end

我的“user_friendship.rb”文件如下所示:

class UserFriendship < ActiveRecord::Base
   belongs_to :user
   belongs_to :friend
end

我应该指出我正在使用 Rails 4。

任何帮助将不胜感激:)

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 shoulda


    【解决方案1】:

    您似乎没有 belongs_to 正在寻找的 Friend 类。我怀疑朋友关系也应该是一个用户对象,在这种情况下你需要这样的东西:

    class UserFriendship < ActiveRecord::Base
      belongs_to :user
      belongs_to :friend, class_name: "User"
    end
    

    【讨论】:

      【解决方案2】:

      如果您使用 Spring 运行测试(即 bin/rspec),则需要在 Gemfile 中手动要求 shoulda-matchers。

      请阅读自述文件以获取更多信息:https://github.com/thoughtbot/shoulda-matchers#rspec

      【讨论】:

        猜你喜欢
        • 2018-02-28
        • 2015-07-01
        • 2023-03-14
        • 1970-01-01
        • 2012-08-22
        • 2012-10-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多