FactoryGirl 具有 has_many 关联的 build_stubbed 策略

ruby

1个回答

写回答

嘉颖

2025-06-29 10:20

+ 关注

AI
AI

标题:使用FactoryGirl的build_stubbed策略创建has_many关联的案例代码

在RAIls应用程序中,我们经常会使用FactoryGirl来生成测试数据。其中一个常见的场景是创建具有关联关系的模型。本文将介绍如何使用FactoryGirl的build_stubbed策略来创建具有has_many关联的模型,并提供相应的案例代码。

## 创建父模型

首先,我们需要创建一个具有has_many关联的父模型。假设我们有一个名为Author的模型,一个Author可以拥有多篇文章。我们可以按照以下步骤进行设置:

Ruby

# app/models/author.rb

class Author < ApplicationRecord</p> has_many :articles

end

## 创建子模型

接下来,我们需要创建一个子模型,即Article模型:

Ruby

# app/models/article.rb

class Article < ApplicationRecord</p> belongs_to :author

end

## 使用FactoryGirl的build_stubbed策略

现在我们可以使用FactoryGirl来生成具有关联关系的模型了。我们将使用build_stubbed策略来创建一个Author对象,并且为该作者创建两篇文章:

Ruby

# spec/factories/authors.rb

FactoryGirl.define do

factory :author do

name { Faker::Name.name }

transient do

articles_count { 2 }

end

after(:build) do |author, evaluator|

author.articles = build_stubbed_list(:article, evaluator.articles_count, author: author)

end

end

end

# spec/factories/articles.rb

FactoryGirl.define do

factory :article do

title { Faker::Book.title }

content { Faker::Lorem.paragraph }

association :author

end

end

在上述代码中,我们首先定义了一个Author工厂,使用transient关键字定义了一个articles_count变量,默认值为2。在after(:build)回调中,我们使用build_stubbed_list方法来创建两篇与该作者关联的文章。

## 测试案例

现在我们可以在测试中使用这个工厂来创建具有has_many关联的模型:

Ruby

# spec/models/author_spec.rb

RSpec.describe Author, type: :model do

it 'has many articles' do

author = FactoryGirl.build_stubbed(:author)

expect(author.articles.count).to eq(2)

end

end

在上述测试中,我们使用FactoryGirl.build_stubbed方法创建了一个作者对象,并断言该作者拥有两篇文章。

通过使用FactoryGirl的build_stubbed策略,我们可以快速、高效地创建具有has_many关联的模型,为测试提供了便利。同时,这也使得我们的测试代码更加清晰和易于维护。

希望本文对你有所帮助!如果你有任何问题或疑问,请随时提问。

举报有用(4)分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号