[英]Testing associations with rspec-rails 3.0.1 and shoulda doesn't work
Currently, with rspec-rails (2.14.2), I test my associations in model specs with the shoulda (3.5.0) gem like so: 目前,使用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
After some research, I hit a wall trying to make association-related assertions work (they all seem to fail). 经过一些研究,我试图让与关联相关的断言起作用(它们似乎都失败了)。
Error message: 错误信息:
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)>'
So my questions are: 所以我的问题是:
shoulda-matchers is the gem that provides association, validation, and other matchers. shoulda-matchers是提供关联,验证和其他匹配器的宝石。
The shoulda gem (which we also make) is for using shoulda-matchers with Test::Unit (and also provides some nice things like contexts and the ability to use strings as test names). shoulda gem(我们也做)是使用带有Test :: Unit的shoulda-matcher(并且还提供了一些很好的东西,比如上下文和使用字符串作为测试名称的能力)。 But if you're on RSpec, you'll want to use shoulda-matchers, not shoulda. 但如果您使用的是RSpec,那么您将需要使用shoulda-matchers,而不是应该使用。
This is the way it works, now with the shoulda-matchers gem and the "expect" syntax 这是它的工作方式,现在使用了shoulda-matchers gem和“expect”语法
describe User, type: :model do
it { is_expected.to belong_to :school }
end
I do not believe you need the gem for the basic associations. 我不相信你需要基本关联的宝石。
You might be having an issues if you haven't actually assigned your user to your school. 如果您尚未将用户实际分配到学校,则可能会遇到问题。 You need to populate the foreign key, not just use the relationship without having done that. 您需要填充外键,而不是仅使用该关系而不执行此操作。
So you may need to do 所以你可能需要这样做
@school = School.new
@user = User.new
@school.users << @user
it { should belong_to :school } # within the user block
or 要么
expect(@user).to belong_to @school
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.