Home>

I'm implementing the chat function in the app I'm making with Rails, and I'm unit testing the model with RSpec.

I want to test that the same group_id and user_id are not saved in the chat group and user intermediate table (group_user).
It doesn't work, so I would appreciate it if you could tell me the solution.

Failures:
  1) GroupUser # create The same user must not be saved more than once in one group
     Failure/Error: expect (group_user.errors [: group_id]). to include ("already exists.")
       expected [] to include "already exists."
     # ./spec/models/group_user_spec.rb:14:in `block (3 levels) in<top (required)>'
Corresponding source code

▼ spec/models/group_user_spec.rb

require'rails_helper'
describe GroupUser do
  describe'#create' do
    it "The same user is not saved more than once in a group" do
      create (: group_user)
      group_user = create (: group_user)
      group_user.valid?
      expect (group_user.errors [: group_id]). to include ("already exists.")
    end
  end
end

▼ spec/factories/group_user.rb

FactoryBot.define do
  factory: group_user do
    group_id {1}
    user_id {1}
    group
    user
  end
end

▼ app/models/group.rb

class Group

▼ app/models/user.rb

class User


▼ app/models/group_user.rb

class GroupUser
What I tried

After trying the same thing as the test in the console, I got the following in the terminal:
I compared this result with the code and found no mistakes.

  • Answer # 1

        create (: group_user)
          group_user = create (: group_user)


    If it is normal, I feel that the second create here was caught in Validation and could not proceed.

    If there are FactoryBot User and Group, the FactoryBot of group_user should be as follows

    FactoryBot.define do
      factory: group_user do
        group
        user
      end
    end

    In group_user_spec.rb, I think it is better to use build for the second validation check.
    For example, I'm wondering if it works as follows.

    describe'#create' do
        let (: user) {create (: user)}
        let (: group) {create (: group)}
        let! (: group_user {create (: group_user, user: user, group: group)}
        it "The same user is not saved more than once in a group" do
          group_user = build (: group_user, user: user, group: group)
          group_user.valid?
          expect (group_user.errors [: group_id]). to include ("already exists.")
        end
      end