通过与Ruby-on-Rails 4.1的关系,遇到RSpec 3.1.0和has_many问题

时间:2014-12-04 02:48:20

标签: ruby-on-rails ruby rspec has-many-through has-many

我正在尝试使用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级)

无论我尝试什么,我似乎无法让这些工作。谁知道我做错了什么?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我最终使用了Shoulda。您也可以通过编写自己的匹配器来解决这个问题。