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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
|
describe "a created instance" do
include FactoryBot::Syntax::Methods
before do
define_model("User")
define_model("Post", user_id: :integer) do
belongs_to :user
end
FactoryBot.define do
factory :user
factory :post do
user
end
end
end
subject { create("post") }
it { should_not be_new_record }
it "assigns and saves associations" do
expect(subject.user).to be_kind_of(User)
expect(subject.user).not_to be_new_record
end
end
describe "a created instance, specifying strategy: :build" do
include FactoryBot::Syntax::Methods
before do
define_model("User")
define_model("Post", user_id: :integer) do
belongs_to :user
end
FactoryBot.define do
factory :user
factory :post do
association(:user, strategy: :build)
end
end
end
subject { create(:post) }
it "saves associations (strategy: :build only affects build, not create)" do
expect(subject.user).to be_kind_of(User)
expect(subject.user).not_to be_new_record
end
end
describe "a custom create" do
include FactoryBot::Syntax::Methods
before do
define_class("User") do
def initialize
@persisted = false
end
def persist
@persisted = true
end
def persisted?
@persisted
end
end
FactoryBot.define do
factory :user do
to_create(&:persist)
end
end
end
it "uses the custom create block instead of save" do
expect(FactoryBot.create(:user)).to be_persisted
end
end
describe "a custom create passing in an evaluator" do
before do
define_class("User") do
attr_accessor :name
end
FactoryBot.define do
factory :user do
transient { creation_name { "evaluator" } }
to_create do |user, evaluator|
user.name = evaluator.creation_name
end
end
end
end
it "passes the evaluator to the custom create block" do
expect(FactoryBot.create(:user).name).to eq "evaluator"
end
end
describe "calling `create` with a block" do
include FactoryBot::Syntax::Methods
before do
define_model("Company", name: :string)
FactoryBot.define do
factory :company
end
end
it "passes the created instance" do
create(:company, name: "thoughtbot") do |company|
expect(company.name).to eq("thoughtbot")
end
end
it "returns the created instance" do
expected = nil
result = create(:company) { |company|
expected = company
"hello!"
}
expect(result).to eq expected
end
end
|