【发布时间】:2014-02-09 10:24:39
【问题描述】:
如何使用 should 匹配器测试这个 ActiveRecord 关系?
型号
class User < ActiveRecord::Base
has_many :articles
end
class Article < ActiveRecord::Base
belongs_to :author, class_name: 'User'
end
测试
describe User do
it { should have_many(:articles) }
end
我收到以下错误:
1) User should have many articles
Failure/Error: it { should have_many(:articles) }
Expected User to have a has_many association called articles (Article does not have a user_id foreign key.)
# ./spec/models/user_spec.rb:4:in `block (2 levels) in <top (required)>'
所以它显然期望关系字段命名为user_id,因为用户类名称。我希望必须有一些测试方法可以用来覆盖这种期望,比如
it { should have_many(:articles).as(:owner) }
但我找不到类似的东西。我错过了什么明显的东西吗?
【问题讨论】:
标签: ruby-on-rails rspec shoulda