1
0
Fork 0
mirror of https://github.com/thoughtbot/factory_bot.git synced 2022-11-09 11:43:51 -05:00
thoughtbot--factory_bot/spec/acceptance/create_spec.rb

135 lines
2.5 KiB
Ruby
Raw Normal View History

describe "a created instance" do
include FactoryBot::Syntax::Methods
before do
define_model('User')
2012-03-09 17:20:38 -05:00
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') }
2013-01-18 13:27:57 -05:00
it { should_not be_new_record }
it "assigns and saves associations" do
2013-01-18 13:27:57 -05:00
expect(subject.user).to be_kind_of(User)
expect(subject.user).not_to be_new_record
end
end
2012-03-09 17:20:38 -05:00
describe "a created instance, specifying strategy: :build" do
include FactoryBot::Syntax::Methods
before do
define_model('User')
2012-03-09 17:20:38 -05:00
define_model('Post', user_id: :integer) do
belongs_to :user
end
FactoryBot.define do
factory :user
factory :post do
2012-03-09 17:20:38 -05:00
association(:user, strategy: :build)
end
end
end
subject { create(:post) }
2012-03-09 17:20:38 -05:00
it "saves associations (strategy: :build only affects build, not create)" do
2013-01-18 13:27:57 -05:00
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
2018-10-07 18:02:54 -04:00
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
2017-09-28 08:17:17 -04:00
describe "a custom create passing in an evaluator" do
before do
define_class("User") do
attr_accessor :name
end
FactoryBot.define do
2017-09-28 08:17:17 -04:00
factory :user do
transient { creation_name { "evaluator" } }
2017-09-28 08:17:17 -04:00
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"
2017-09-28 08:17:17 -04:00
end
end
describe "calling `create` with a block" do
include FactoryBot::Syntax::Methods
before do
2012-03-09 17:20:38 -05:00
define_model('Company', name: :string)
FactoryBot.define do
factory :company
end
end
it "passes the created instance" do
2012-03-09 17:20:38 -05:00
create(:company, name: 'thoughtbot') do |company|
2013-01-18 13:27:57 -05:00
expect(company.name).to eq('thoughtbot')
end
end
it "returns the created instance" do
expected = nil
2013-01-18 13:27:57 -05:00
result = create(:company) do |company|
expected = company
"hello!"
2013-01-18 13:27:57 -05:00
end
expect(result).to eq expected
end
end