如何使用factorygirl关联user_id

时间:2016-09-12 22:17:55

标签: ruby-on-rails factory-bot

我正在学习使用Rails测试工具进行测试,主要是:rspec, factory_girl, shoulda, and faker gems。

我想测试has_onebelongs_to关联。我有user.rb(包含name)和address.rb(包含streetcityuser_id个模型。

我试图弄清楚如何使用fakers创建假联想。我想创建一个虚假的街道并将其与假用户关联,但我无法弄清楚如何在spec/factories/addresses.rb

上做到这一点

这就是我目前所拥有的:

FactoryGirl.define do
  factory :address do
    street    {Faker::Address.street_address}
    city      {Faker::Address.city}
    #Creates fake user and use that user's id for user_id)#
    user = build(:user, name: "Joe", id: 2)
    user_id   {user.id}
  end
end

这是spec / models / address_spec.rb

require 'rails_helper'

RSpec.describe Address, type: :model do
  it "has a valid factory" do
    address = build(:address)
    expect(address).to be_valid
  end
  it {should belong_to(:user)}
end

运行时,显示add_attribute': wrong number of arguments (given 3, expected 1..2) (ArgumentError)错误。我尝试删除参数上的id,然后执行了user = build(:user, name: "Joe"),但仍显示相同的错误消息。

如果我在addresses工厂中不包含用户线,则传递。我确认地址为belongs_to :user,用户为has_one :address

是否可以为假user.id生成假关联和关联地址?我也想测试Address的{​​{1}}。

编辑 - 以下是相关工厂和模型:

工厂

addresses.rb

user_id

users.rb的

FactoryGirl.define do
  factory :address do
    street    {Faker::Address.street_address}
    city      {Faker::Address.city}
    user
  end
end

规格/模型

address_spec.rb

FactoryGirl.define do
  factory :user do
    name      {Faker::Name.name}
  end
end

运行address_spec.rb

时出错
require 'rails_helper'

RSpec.describe Address, type: :model do
  it "has a valid factory" do
    association user
    specific_user = build(:user, name: 'Joe')
    address = build(:address, specific_user)
    expect(address).to be_valid
  end
  it {should belong_to(:user)}
end

1 个答案:

答案 0 :(得分:1)

我认为你建立关联的方式是不正确的。请参阅https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations

如果你想要一个更具体的相关用户,例如名字:Joe,id:2,那么最好在规范中做到这一点。

厂:

FactoryGirl.define do
  factory :address do
    street    {Faker::Address.street_address}
    city      {Faker::Address.city}
    user
  end
end

规格:

 it "has a valid factory" do
    specific_user = build(:user, name: 'Joe')
    address = build(:address, specific_user)
    expect(address).to be_valid
 end