Search code examples
ruby-on-railsrspecruby-on-rails-5

Rspec tests fail even though everything works fine manually


I'm using RSpec to test my Rails5 app and am having problems regarding deleting or updating objects. That is, the app functions correctly but if I test some of these functions the tests fail.

Test 1

let!(:user) { create(:user) }
let!(:admin) { create(:admin) }
let!(:new_name) { 'new name' }

it 'changes user name' do
    visit(user_path(user))
    click_on('Edit')
    expect(current_path).to eq(edit_user_as_admin_path(user))
    fill_in('Name', with: new_name)
    click_on('Update')
    expect(current_path).to eq(user_path(user))
    expect(user.name).to eq(new_name)
end

If I go through it in my browser as an admin I can update the attributes just fine.

Test 2

  let!(:user){create(:user)}
  let!(:friend){create(:user)}

  before(:each){sign_in friend
    visit(user_path(user))
    click_on('Add Friend')
    sign_in user
  }

  it 'is accepted' do
    visit(user_path(user))
    click_on('Accept')
    expect(user.friend_requests).to be_empty
 end

Here again, if I do it manually and check everything with byebug or rails console the user does not have a friend_request anymore. So those two are system specs and I wonder if misunderstood how to test correctly. Since I read system specs test the whole system I thought by simulating the user behaviour I can also check if the controller actions are executed properly.

But also in my model specs it's not working like it should be:

Test 3

let!(:user){create(:user)}
let!(:post) {create(:post)}

it 'is deleted if user is deleted' do
  user.posts << post
  expect do
    user.destroy
  end.to change(user.posts,:count).by(-1)
end

I thought this would be an approproiate test for a model since it should work because of a dependent: :destroy.

Now I wonder if I have mistakes in my code that I just can't seem to figure out or if I have a wrong concept in my brain.

Any help and clarification would be appreciated! Thank you.


Solution

  • You need to reload your user object, via user.reload.friend_requests. The in-memory object in your test hasn't been hydrated with any updates.