我正在尝试使用RSpec来测试模型之间的关系。我有两个模型:
class User < ActiveRecord::Base
has_many :user_roles
has_many :roles, through: :user_roles
end
和
class Role < ActiveRecord::Base
has_many :user_roles
has_many :users, through: :user_roles
end
通过以下课程:
class UserRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
我的RSpec代码是:
describe User do
it { is_expected.to have_many(:user_roles) }
it { is_expected.to have_many(:roles).through(:user_roles) }
end
这两个抛出错误:
1)用户应该有很多:user_roles
失败/错误:{is_expected.to have_many(:user_roles)}
期望#回复has_many?
#./spec/models/user_spec.rb:49:in'块(2级)in'
2)用户 失败/错误:{is_expected.to have_many(:roles)。through(:user_roles)} NoMethodError: '
中的未定义方法through' for #<RSpec::Matchers::BuiltIn::Has:0x007fe1cd003ac8>
# ./spec/models/user_spec.rb:50:in
块(2级)
无论我尝试什么,我似乎无法让这些工作。谁知道我做错了什么?
感谢您的帮助!
答案 0 :(得分:0)
我最终使用了Shoulda。您也可以通过编写自己的匹配器来解决这个问题。