Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load Globalize translation fixtures to test models?

I'm using the gobalize gem 4.0.3 in Rails 4.1.12.

I have a Post model and I've run the Post.create_translation_table! migration supplied by globalize to set up a post_translations table.

Now I want to automatically load translations from my fixture files. Fixtures support label references for associations so I have this:

# spec/fixtures/posts.yml

my_first_post:
  author: dave

# spec/fixtures/post_translations.yml

my_first_post_translation:
  locale: en    
  title: My first post
  content: What a time to be alive!
  post: my_first_post

# spec/models/post_spec

require 'rails_helper'

RSpec.describe Post, type: :model do
  fixtures('post/translations', :posts, :authors)

  subject(:post) { posts(:my_first_post) }

  it "has an author" do
    expect(post.author).to eq(authors(:dave))
  end

  it "has a title" do
    binding.pry
    expect(post.title).to be_present
  end
end

But running RSpec throws the following error:

 Failure/Error: Unable to find matching line from backtrace
 ActiveRecord::StatementInvalid:
   SQLite3::SQLException: table post_translations has no column named post: INSERT INTO "post_translations" ("locale", "title", "content", "post", "created_at", "updated_at", "id") VALUES ('en', 'My first post', 'This is some compelling english content', 'my_first_post', '2015-08-21 10:23:27', '2015-08-21 10:23:27', 626768522)

A similar error occurs if I do the inverse (i.e. post_translation: my_first_translation in posts.yml)

How do I get the magic back?

like image 455
Dave Nolan Avatar asked Dec 08 '22 01:12

Dave Nolan


1 Answers

Solution

  1. Move fixtures/post_translations.yml to fixtures/post/translations.yml
  2. The key for the association in my_first_translation is globalized_model

So you will end up with this:

<!-- language: yml -->
# spec/fixtures/posts.yml

my_first_post:
  author: dave

# spec/fixtures/post/translations.yml

my_first_post_translation:
  locale: en
  title: My first post
  content: What a time to be alive!
  globalized_model: my_first_post

Explanation

  1. The translation model is Post::Translation. The namespacing means that the location of the Post::Translation fixtures must follow the same nesting conventions as a model in app/models.

  2. The association name on Post::Translation (and any globalize translation model) is globalized_model. ActiveRecord::FixtureSet uses the association name to recognise the fixture key as an association.

like image 94
Dave Nolan Avatar answered Jan 21 '23 09:01

Dave Nolan