Steve
Steve

Reputation: 2854

How do I test associations in models with RSpec in Rails 5?

I'm new to Rails 5, and trying to test an extremely simple database model, but I can't seem to get it right. I'm trying to test the has_many association.

The model code looks like this:

app/models/database_models/response.rb

module DatabaseModels
  class Response < ApplicationRecord

    has_many :question_responses, :class_name => 'DatabaseModels::
QuestionResponse'

  end
end

The spec (RSpec) looks like this

spec/models/screener_response_spec.rb

require 'rails_helper'

describe DatabaseModels::Response, type: :model do
  it { is_expected.to have_many(:question_responses) }
end

It fails with:

expected #<DatabaseModels::Response:0x007fd91ccda210> to respond to `has_many?`

What am I doing wrong?

Upvotes: 1

Views: 3402

Answers (1)

max
max

Reputation: 102036

One way to test this would be to test the actual behaviour:

require 'rails_helper'

describe DatabaseModels::Response, type: :model do

  let(:response) { described_class.new }
  it 'has many question responses' do
    expect( response.question_responses.new ).to be_a_new DatabaseModels::
QuestionResponse 
  end
end

Otherwise you can use reflection which is basically what shoulda does:

require 'rails_helper'

describe DatabaseModels::Response, type: :model do
  it 'has many question responses' do
    relation = described_class.reflect_on_association(:question_resp‌​onses)
    expect(relation.macro).to eq :has_many
  end
end

Upvotes: 1

Related Questions