ruby-on-rails - 如何加载 Globalize 翻译装置来测试模型?

标签 ruby-on-rails ruby-on-rails-4 activerecord fixtures globalize

我在 Rails 4.1.12 中使用 gobalize gem 4.0.3。

我有一个 Post 模型,并且我运行了 Post.create_translation_table! 提供的 globalize 迁移来设置 post_translations 表。

现在我想从我的夹具文件中自动加载翻译。夹具支持 label references for associations 所以我有这个:

# 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

但是运行 RSpec 会引发以下错误:
 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)

如果我执行相反的操作(即 post_translation: my_first_translation 中的 posts.yml ),则会发生类似的错误

怎么找回魔法?

最佳答案

解决方案

  • fixtures/post_translations.yml 移动到 fixtures/post/translations.yml
  • my_first_translation 中关联的关键是 globalized_model

  • 所以你最终会得到这个:
    <!-- 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
    

    解释
  • 翻译模型是 Post::Translation 。命名空间意味着 Post::Translation 固定装置的位置必须遵循与 app/models 中的模型相同的嵌套约定。
  • Post::Translation(以及任何 globalize 翻译模型)上的关联名称是 globalized_modelActiveRecord::FixtureSet uses the association name to recognise the fixture key as an association
  • 关于ruby-on-rails - 如何加载 Globalize 翻译装置来测试模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32138228/

    相关文章:

    ruby-on-rails - 如何正确将此 SQL 转换为 ActiveRecord?

    ruby-on-rails - 在 Rails 4 中输出特殊字符

    ruby-on-rails - 在命名空间中设计 - ActionController::RoutingError(没有路由匹配 {:action= >"new", :controller= >"devise/sessions"})

    sql - 按属性将 Rails 查询分组到数组中

    ruby-on-rails - Rails 测试单元 : How to find an unused id for a model

    ruby - 将 Array#select 转换为 rails 4 中的事件记录查询

    php - 模型返回空值

    ruby-on-rails - 连接两个表以获取数据 rails 4

    ruby-on-rails - Rails 应用程序中的 Postgres LIKE

    mysql - rails 3 : How to make a join in mysql over 3 tables (with :through in the model)