Rspec, check for association

I am trying to check the association.

I have two classes:

class Survey < ActiveRecord::Base
  has_many :users, through: :users_surveys
  has_many :users_surveys

  def update_or_create_result(user_id, result, target)
    user_survey = users_surveys.find_or_create_by(user_id: params[:user_id])
    if survey_passed?(result, target)
      user_survey.completed!
    end
  end
end

class User < ActiveRecord::Base
  has_many :surveys, through: :users_surveys
  has_many :users_surveys
end

class UsersSurvey < ActiveRecord::Base
  belongs_to :user
  belongs_to :survey
end

How can I test with RSpec if an association is created between the survey and the user?

+4
source share
4 answers

Assuming you have userand variables survey, it's that simple:

user.surveys.should include(survey)

Since your question is a bit unclear, my answer checks to see if a link is created between the actual two records.

+2
source

I just want to emphasize that the current nex syntax for RSpec is as follows :

describe User do
  it { is_expected.to have_many(:surveys) } # shortcut for expect(subject).to
end

describe Survey do
  it { is_expected.to belong_to(:user) }
end

should considered the old syntax for quite a few years :)

+2
source

shoulda-matchers gem , :

describe User do
  it { should have_many(:surveys) }
end

- gem-o-phobia , ActiveRecord::Reflection, :

describe User do
  it "should have_many :surveys" do
    expect(User.reflect_on_association(:surveys).macro).to eq :has_many
  end
end

describe Survey do
  it "should belong_to user" do
    expect(Survey.reflect_on_association(:user).macro).to eq :belongs_to
    expect(Survey.column_names).to include :user_id
  end
end

, , , , , A B.

+2

Shoulda,

describe User do
  it { should have_many(:surveys) }
end

describe Survey do
  it { should belong_to(:user) }
end

, has_many :through, ,

describe User do
  it { should have_many(:surveys).through(:user_survey) }
end

Shoulda,

describe User do
  let(:user) { User.new }

  it "should define the association" do
    expect(user).to have(:no).errors_on(:surveys)
  end
end

describe Survey do
  let(:user) { User.new }
  let(:survey) { user.surveys.create }

  it "should define the association" do
    expect(survey).to have(:no).errors_on(:user)
  end
end
+1
source

Source: https://habr.com/ru/post/1625810/


All Articles