简体   繁体   中英

Having trouble with RSpec 3.1.0 and has_many through relationship with Ruby-on-Rails 4.1

I am trying to use RSpec to test my relationships between Models. I have two models:

class User < ActiveRecord::Base
  has_many :user_roles
  has_many :roles, through: :user_roles
end

and

class Role < ActiveRecord::Base
  has_many :user_roles
  has_many :users, through: :user_roles
end

with a through class of:

class UserRole < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
end

My RSpec code is:

describe User do
  it { is_expected.to have_many(:user_roles) }
  it { is_expected.to have_many(:roles).through(:user_roles) }
end

Both of these throw errors:

1) User should have many :user_roles Failure/Error: it { is_expected.to have_many(:user_roles) } expected # to respond to has_many? # ./spec/models/user_spec.rb:49:in `block (2 levels) in '

2) User Failure/Error: it { is_expected.to have_many(:roles).through(:user_roles) } NoMethodError: undefined method through' for #<RSpec::Matchers::BuiltIn::Has:0x007fe1cd003ac8> # ./spec/models/user_spec.rb:50:in block (2 levels) in '

No matter what I try I can't seem to get these to work. Anyone know what I am doing wrong?

Thanks for any help!

I ended up using Shoulda. You could also solve this problem by programming your own matchers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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