Tonys
Tonys

Reputation: 3399

How do you set this rspec example on has and belongs to many association

Having trouble framing this assertion in Rspec for my rails app. A User has a habtm association to Role, I want to assert that, after my test a User should should be associated to a role with a title of "Superuser". In the rails console.

user.roles.where(title: "Superuser").any?
=> true

How would that look in rspec what I'd like to say is 'user has a role titled "Superuser"'

thanks,

Upvotes: 0

Views: 332

Answers (2)

bishal
bishal

Reputation: 716

I have been looking to setup a spec to test the has_and_belongs_to_many relationship between two models myself. And if anyone is looking to test the relationship this might be helpful to them:

it "should have and belong many to Categories" do
  assc = described_class.reflect_on_association(:categories)
  expect(assc.macro).to eq :has_and_belongs_to_many
end

Upvotes: 0

Veraticus
Veraticus

Reputation: 16084

How about something like this:

user.roles.where(title: "Superuser").should_not be_empty

Upvotes: 1

Related Questions