[英]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)>'
所以我的問題是:
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.