Rspec,测试关联的存在

Rob*_*ali 5 rspec ruby-on-rails ruby-on-rails-4

我正在尝试测试一个关联.

我有这两个类:

class Survey < ActiveRecord::Base
  has_many :users, through: :users_surveys
  has_many :users_surveys

  def update_or_create_result(user_id, result, target)
    user_survey = users_surveys.find_or_create_by(user_id: params[:user_id])
    if survey_passed?(result, target)
      user_survey.completed!
    end
  end
end

class User < ActiveRecord::Base
  has_many :surveys, through: :users_surveys
  has_many :users_surveys
end

class UsersSurvey < ActiveRecord::Base
  belongs_to :user
  belongs_to :survey
end
Run Code Online (Sandbox Code Playgroud)

如果创建调查和用户之间的关联,我如何使用RSpec进行测试?

And*_*eko 5

只是想强调一下,当前 RSpec 的 nex 语法如下

describe User do
  it { is_expected.to have_many(:surveys) } # shortcut for expect(subject).to
end

describe Survey do
  it { is_expected.to belong_to(:user) }
end
Run Code Online (Sandbox Code Playgroud)

should 现在被认为是旧语法好几年了:)


Mar*_*pka 2

假设您有usersurvey变量,就这么简单:

user.surveys.should include(survey)
Run Code Online (Sandbox Code Playgroud)

由于您的问题有点不清楚,我的答案检查是否创建了实际两条记录之间的关联。