File: build_list_spec.rb

package info (click to toggle)
ruby-factory-bot 6.5.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,372 kB
  • sloc: ruby: 7,827; makefile: 6
file content (68 lines) | stat: -rw-r--r-- 1,702 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
describe "build multiple instances" do
  before do
    define_model("Post", title: :string, position: :integer)

    FactoryBot.define do
      factory(:post) do |post|
        post.title { "Through the Looking Glass" }
        post.position { rand(10**4) }
      end
    end
  end

  context "without default attributes" do
    subject { FactoryBot.build_list(:post, 20) }

    its(:length) { should eq 20 }

    it "builds (but doesn't save) all the posts" do
      subject.each do |record|
        expect(record).to be_new_record
      end
    end

    it "uses the default factory values" do
      subject.each do |record|
        expect(record.title).to eq "Through the Looking Glass"
      end
    end
  end

  context "with default attributes" do
    subject { FactoryBot.build_list(:post, 20, title: "The Hunting of the Snark") }

    it "overrides the default values" do
      subject.each do |record|
        expect(record.title).to eq "The Hunting of the Snark"
      end
    end
  end

  context "with a block" do
    subject do
      FactoryBot.build_list(:post, 20, title: "The Listing of the Block") do |post|
        post.position = post.id
      end
    end

    it "correctly uses the set value" do
      subject.each do |record|
        expect(record.position).to eq record.id
      end
    end
  end

  context "with a block that receives both the object and an index" do
    subject do
      FactoryBot.build_list(:post, 20, title: "The Indexed Block") do |post, index|
        post.position = index
      end
    end

    it "correctly uses the set value" do
      subject.each_with_index do |record, index|
        expect(record.position).to eq index
      end
    end
  end
end