###環境
- MySQL 5.7
- Ruby 2.3.3
- Rails 5.0.1
- Rspec / FactoryGirl / DatabaseRewinder
###前提・実現したいこと
掲示板のような機能で全文検索を実装しようとしています。
テストを走らせるとSTORED GENERATEDカラムがNULLになっていて困っています。
Topicモデルにtitle
とdescritpion
を持たせており、この二つをCONCATしたカラム(fulltext_column
とします)を検索対象としています。
migration
fulltext_column
を追加するmigrationです。
ruby
1class AddFulltextColumnToTopics < ActiveRecord::Migration[5.0] 2 def up 3 execute "ALTER TABLE topics ADD fulltext_column TEXT AS (CONCAT_WS(' ', title, description)) STORED COMMENT '検索用カラム' AFTER description, ADD FULLTEXT KEY (fulltext_column) WITH PARSER ngram" 4 end 5 6 def down 7 remove_column :topics, :fulltext_column 8 end 9end
なお、ngram_token_sizeは2に設定してあります。
Topicモデル
実際のコードとは少し異なりますがMATCH AGAINSTで検索します。
ruby
1class Topic < ApplicationRecord 2 scope :search_words, ->(words) do 3 where('MATCH(fulltext_column) AGAINST (? IN BOOLEAN MODE)', words) 4 end 5end
テストコード
ruby
1RSpec.describe Topic, type: :model do 2 describe '.search_words(words)' do 3 subject { Topic.search_words(words).count } 4 let(:words) { 'ほげ ふが' } 5 6 before do 7 FactoryGirl.create :topic, title: 'ほげ', description: 'ふが' 8 end 9 10 it { is_expected.to eq 1 } 11 end 12end
###発生している問題・エラーメッセージ
「ほげ」にも「ふが」にもマッチせず結果は0件となってしまっています。
1) Topic.search_words(words) should eq 1 Failure/Error: it { is_expected.to eq 1 } expected: 1 got: 0 (compared using ==)
###試したこと
DatabaseRewinderのstrategyを:truncation
に設定してみたが解決できなかった。
before
内のFactoryGirl.create
後にbinding.pry
で値を確認してみたところ、
fulltext_column
はnil
でした。
rails console, FactoryGirlでデータを投入した場合はfulltext_column
にデータが格納されることは確認できました。
rspecの場合のみfulltext_column
がCONCATで生成されていないような感触です。
知見のある方、御教授をお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。