Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec/Mongoid: Expect to change count on embedded models

I have two Mongoid models: User and EmailAccounts. The latter is embedded in the User model. That configuration should be fine because it works generally. Now I'm trying to write an integration test for my user edit form that looks like this:

describe 'Add EmailAccount' do
  it 'Adds an email account', js: true do
    user = FactoryGirl.create(:user_without_email_accounts)
    visit edit_user_path(user)
    expect{
      click_link 'New Email Account'
      within '.nested-fields' do
        fill_in 'Account Name', with: 'New Email Account'
        fill_in 'Other Field', with: 'Other Data'
      end
      click_button 'Save'
    }.to change(EmailAccount, :count).by(1)
  end
end

Because EmailAccount is an embedded model the change of count is always 0. Can I check for a change of the EmailAccount counter in any similar way? Or do I have to go a different way? This won't work neither:

      }.to change(user.email_accounts, :count).by(1)
like image 503
Phil Avatar asked Oct 11 '12 12:10

Phil


2 Answers

I had the exact same issue and managed to solve it by using a combination the answers posted here.

expect {
  #action 
}.to change { foo.reload.bars.count }.by(1)
like image 152
Arjan Avatar answered Oct 07 '22 16:10

Arjan


Edited with new answer:

I've been able to use this syntax in my spec of a Mongoid document:

expect {
  #action
}.to change { Model.count }.by(1)

Note that the count statement is within brackets and doesn't use a :count parameter.

like image 25
Eric Parshall Avatar answered Oct 07 '22 14:10

Eric Parshall