require 'rails_helper'


RSpec.describe 'post_similarity:calc' do
  include RakeTaskHelper

  it 'calculates similarities from active tags only' do
    # 必要最低限のデータ
    t1 = Tag.create!(name: "t1")
    t2 = Tag.create!(name: "t2")
    t3 = Tag.create!(name: "t3")
    deprecated_tag = Tag.create!(name: 'deprecated', deprecated_at: Time.current)

    p1 = Post.create!(url: "https://example.com/1")
    p2 = Post.create!(url: "https://example.com/2")
    p3 = Post.create!(url: "https://example.com/3")

    # kept スコープが絡むなら、PostTag がデフォで kept になる前提
    PostTag.create!(post: p1, tag: t1)
    PostTag.create!(post: p1, tag: t2)

    PostTag.create!(post: p2, tag: t1)
    PostTag.create!(post: p2, tag: t3)

    PostTag.create!(post: p3, tag: t3)
    PostTag.create!(post: p1, tag: deprecated_tag)
    PostTag.create!(post: p2, tag: deprecated_tag)

    expect { run_rake_task("post_similarity:calc") }
      .to change { PostSimilarity.count }.from(0)

    ps = PostSimilarity.find_by!(post_id: p1.id, target_post_id: p2.id)
    ps_rev = PostSimilarity.find_by!(post_id: p2.id, target_post_id: p1.id)
    expect(ps_rev.cos).to eq(ps.cos)
    expect(ps.cos).to be_within(0.0001).of(0.5)
  end
end
