CaptainAwesomeDi
CaptainAwesomeDi

Reputation: 21

Rails Minitest Has Many And Belongs To Model Test ActiveRecord::UnknownPrimaryKey Error

When I try to run minitest with simpleCov, I want the join table model UserMessages to be covered.

I have setup fixture, to run test and keep getting an ActiveRecord::UnknownPrimaryKey error. This is expected since I don't have a primary key on the UserMessage table.

Is there a way to bypass this error and also have coverage on the UserMessage model?

MODELS:

class User < ApplicationRecord
  has_and_belongs_to_many :messages, join_table "users_messages"
end

class Message < ApplicaitonRecord
  has_and_belongs_to_many :users, join_table: "users_messages"
end

class UserMessage <ApplicationRecord
  self.table_name = "users_messsages"
  belongs_to :user
  belongs_to :messages
end

FIXTURES:

User:

default:
  name: test

Message:

default:
  message: hello world!
  users:
   - default

UserMessage:

default:
  user: default
  message: default

TEST:

require "test_helpers"
class UserMessageTest < ActiveSupport::TestCase
 def setup
  @user_message = user_message(:default) # The error happens here: ActiveRecord::UnknownPrimaryKey:\ 
                                         # Unknown primary key for table users_messages in model \      
                                         # UserMessage
 end

 test "is valid" do
  assert @user_message.valid?, "Should be valid"
 end
end

Upvotes: 0

Views: 502

Answers (1)

CaptainAwesomeDi
CaptainAwesomeDi

Reputation: 21

I just realized how bad this is.

I could just not use the fixture to fix the problem.

require "test_helper"
UserMessageTest < AcitveSupport::TestCase
  def setup
   @user_message = UserMessage.new(user_id: User.first.id,
                                   message_id: Message.first.id)

  end

  test "could save successfully" do
   assert @user_message.save
  end
end

And the test passes!

Upvotes: 1

Related Questions