繁体   English   中英

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

[英]Testing associations with rspec-rails 3.0.1 and shoulda doesn't work

目前,使用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 #<RSpec::ExampleGroups::School:0x007f8a4c7a68d0>
     # ./spec/models/user.rb:4:in `block (2 levels) in <top (required)>'

所以我的问题是:

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

shoulda-matchers是提供关联,验证和其他匹配器的宝石。

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

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

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

所以你可能需要这样做

@school = School.new
@user = User.new
@school.users << @user

it { should belong_to :school } # within the user block

要么

expect(@user).to belong_to @school

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM