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
|
describe "a built 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 { build(:post) }
it { should be_new_record }
context "when the :use_parent_strategy config option is set to false" do
it "assigns and saves associations" do
with_temporary_assignment(FactoryBot, :use_parent_strategy, false) do
expect(subject.user).to be_kind_of(User)
expect(subject.user).not_to be_new_record
end
end
end
context "when the :use_parent_strategy config option is set to true" do
it "assigns but does not save associations" do
with_temporary_assignment(FactoryBot, :use_parent_strategy, true) do
expect(subject.user).to be_kind_of(User)
expect(subject.user).to be_new_record
end
end
end
end
describe "a built instance with strategy: :create" 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: :create)
end
end
end
subject { build(:post) }
it { should 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 "calling `build` 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 built instance" do
build(:company, name: "thoughtbot") do |company|
expect(company.name).to eq("thoughtbot")
end
end
it "returns the built instance" do
expected = nil
result = build(:company) { |company|
expected = company
"hello!"
}
expect(result).to eq expected
end
end
|