如何通过factory_girl与两个不同的数据库建立联系?

时间:2016-09-08 08:12:56

标签: ruby-on-rails rspec factory-bot

现在我有两个rails应用程序。名称是:

  • App1的
  • App2的

我想在App1中进行rspec测试。也想在App2中操作数据。

App2中的模型:

# User
class User < ActiveRecord::Base
  has_many :posts
end

# Post
class Post < ActiveRecord::Base
  belongs_to :user
end

App1中的factory_girl文件:

# spec/factories/users.rb
FactoryGirl.define do
  factory :user, :class => App2::User do
    name 'user_name'
  end
end

# spec/factories/posts.rb
FactoryGirl.define do
  factory :post, :class => App2::Post do
    association :user, factory: :user
    name 'post_name'
  end
end

如果我在App1中的spec文件中创建数据:

# spec/my_test_spec.rb
require 'rails_helper'
RSpec.describe MyTest do
  let(:app2_post) { create(:post) }
  ...
end

它说:

Failure/Error: let(:app2_post) { create(:post) }

NoMethodError:
  undefined method 'user=' for #<App2::Post:0x000000092933>
  Did you mean? user_id=
                user_id
...

:user不是App1中的类,而是App2中的类。如果我尝试association App2::User, factory: :user,也会出错。

然后如何在此处编写关联:association :user, factory: :user

0 个答案:

没有答案