当前,使用rspec-rails(2.14.2),我应该使用Shoulda(3.5.0)gem在模型规范中测试我的关联,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 | # 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 2 3 4 5 | 1) User Failure/Error: it { is_expected.to belong_to :school } NoMethodError: undefined method `belong_to' for #<RSpec::ExampleGroups::School:0x007f8a4c7a68d0> # ./spec/models/user.rb:4:in `block (2 levels) in <top (required)>' |
所以我的问题是:
这是它的工作方式,现在使用shoulda-matchers gem和" expect "语法
1 2 3 | describe User, type: :model do it { is_expected.to belong_to :school } end |
shoulda-matchers是提供关联,验证和其他匹配器的ruby。
Shoulda gem(我们也制造)是用于在Test :: Unit中使用shoulda-matchers(并且还提供了一些不错的东西,例如上下文以及使用字符串作为测试名称的功能)。但是,如果您使用的是RSpec,则将要使用Shoulda-matchers,而不是Shoulda。
我认为您不需要基本关联的ruby。
如果您实际上尚未将用户分配到学校,则可能会遇到问题。您需要填充外键,而不是不这样做就直接使用该关系。
所以您可能需要做
1 2 3 4 5 | @school = School.new @user = User.new @school.users << @user it { should belong_to :school } # within the user block |
或
1 | expect(@user).to belong_to @school |