discourse-translator/spec/services/discourse_ai_spec.rb
Natalie Tay 7fc45d5be8
DEV: Move translation custom fields into their own tables (#201)
Currently, `Topic` and `Post` have detected_language and translations in custom fields, e.g.
```
post.custom_fields[DiscourseTranslator::DETECTED_LANG_CUSTOM_FIELD]
post.custom_fields[DiscourseTranslator::TRANSLATED_CUSTOM_FIELD]
topic.custom_fields[DiscourseTranslator::DETECTED_LANG_CUSTOM_FIELD]
topic.custom_fields[DiscourseTranslator::TRANSLATED_CUSTOM_FIELD]
```

We are moving this into 4 tables/models
```
post has_one :content_locale, class_name: "DiscourseTranslator::PostLocale"
post has_many :translations, class_name: "DiscourseTranslator::PostTranslation"
topic has_one :content_locale, class_name: "DiscourseTranslator::TopicLocale"
topic has_many :translations, class_name: "DiscourseTranslator::TopicTranslation"
```

Since there are a lot of duplicates, this is implemented on the `Post` and `Topic` using a `Concern`, and any future translatable content can inherit this concern.

This PR also gets rid of the previous N+1 which happens when determining if the 🌐 translate button should appear for each post.
2025-02-10 12:29:07 +08:00

53 lines
1.6 KiB
Ruby

# frozen_string_literal: true
require "rails_helper"
describe DiscourseTranslator::DiscourseAi do
fab!(:post)
before do
Fabricate(:fake_model).tap do |fake_llm|
SiteSetting.public_send("ai_helper_model=", "custom:#{fake_llm.id}")
end
SiteSetting.ai_helper_enabled = true
SiteSetting.translator_enabled = true
SiteSetting.translator = "DiscourseAi"
end
describe ".language_supported?" do
it "returns true when detected language is different from i18n locale" do
I18n.stubs(:locale).returns(:xx)
expect(described_class.language_supported?("any-language")).to eq(true)
end
it "returns false when detected language is same base language as i18n locale" do
I18n.stubs(:locale).returns(:en_GB)
expect(described_class.language_supported?("en")).to eq(false)
end
end
describe ".detect!" do
it "stores the detected language" do
locale = "de"
DiscourseAi::Completions::Llm.with_prepared_responses(["<language>de</language>"]) do
DiscourseTranslator::DiscourseAi.detect!(post)
end
expect(post.detected_locale).to eq locale
end
end
describe ".translate" do
before { post.set_detected_locale("de") }
it "translates the post and returns [locale, translated_text]" do
DiscourseAi::Completions::Llm.with_prepared_responses(
["<translation>some translated text</translation>"],
) do
locale, translated_text = DiscourseTranslator::DiscourseAi.translate(post)
expect(locale).to eq "de"
expect(translated_text).to eq "some translated text"
end
end
end
end