我目前正在编写 RSpec 测试来验证 Rails 应用程序中的关联。具体来说,我试图通过 Artist_albums 连接表/模型确保 Artist 模型与专辑具有正确的关联。然而,尽管在我的模型中正确设置了关联,但我的测试还是失败了。
RSpec.describe Artist, type: :model do
describe 'associations' do
it 'should have albums through artist_albums' do
artist_association = described_class.reflect_on_association(:albums)
expect(artist_association.macro).to eq(:has_many)
expect(artist_association.through_reflection.name).to eq(:artist_albums)
end
end
end
错误如下:
expect(album_association.options[:dependent]).to eq(:destroy)
expected: :destroy
got: nil
(compared using ==)
型号:
class Artist < ApplicationRecord
has_many :artist_albums
has_many :albums, through: :artist_albums
end
class ArtistAlbum < ApplicationRecord
belongs_to :artist
belongs_to :album
end
class Album < ApplicationRecord
has_many :artist_albums
has_many :artists, through: :artist_albums
end
尽管按预期设置了关联,测试仍因错误而失败。我不知道为什么会发生这种情况。任何有关如何解决和解决此问题的见解或建议将不胜感激!谢谢你。
我需要调用
through_reflection
来访问选项哈希:
expect(artist_association.through_reflection.options[:dependent]).to eq(:destroy)