与rspec-rails 3.0.1和shoulda的测试关联不起作用

目前,使用rspec-rails(2.14.2),我使用shoulda(3.5.0)gem测试模型规范中的关联,如下所示:

# app/models/user.rb class User < ActiveRecord::Base belongs_to :school end # spec/models/user_spec.rb describe User do it { should belong_to :school } end 

经过一些研究,我试图让与关联相关的断言起作用(它们似乎都失败了)。

错误信息:

 1) User Failure/Error: it { is_expected.to belong_to :school } NoMethodError: undefined method `belong_to' for # # ./spec/models/user.rb:4:in `block (2 levels) in ' 

所以我的问题是:

  1. 你可以测试没有shoulda gem的协会吗? 根据我在“expect”语法中看到的内容,这似乎不可行。
  2. 对于每个人来说,shoulda gem是否会与rspec 3.0.1打破? 有解决方法吗?

shoulda-matchers是提供关联,validation和其他匹配器的gem。

shoulda gem(我们也做)是使用带有Test :: Unit的shoulda-matcher(并且还提供了一些很好的东西,比如上下文和使用字符串作为测试名称的能力)。 但如果您使用的是RSpec,那么您将需要使用shoulda-matchers,而不是应该使用。

这是它的工作方式,现在使用了shoulda-matchers gem和“expect”语法

 describe User, type: :model do it { is_expected.to belong_to :school } end 

我不相信你需要基本关联的gem。

如果您实际上没有将您的用户分配到您的学校,则可能会遇到问题。 您需要填充外键,而不是仅使用该关系而不执行此操作。

所以你可能需要这样做

 @school = School.new @user = User.new @school.users << @user it { should belong_to :school } # within the user block 

要么

 expect(@user).to belong_to @school