-
-
Save ezekg/7738249c671e48c0372884c847e2559f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "bundler/inline" | |
gemfile true do | |
git_source(:github) { "https://github.com/#{_1}.git" } | |
source "https://rubygems.org" | |
gem "factory_bot", "~> 6.0" | |
gem "activerecord" | |
gem "sqlite3" | |
end | |
require "active_record" | |
require "factory_bot" | |
require "minitest/autorun" | |
require "logger" | |
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
ActiveRecord::Schema.define do | |
create_table :posts, force: true do |t| | |
t.string :title | |
t.string :body | |
end | |
end | |
class Post < ActiveRecord::Base; end | |
FactoryBot.define do | |
NIL_TITLE = Object.new # sentinel values to differentiate explicit nils from implicit nils | |
NIL_BODY = Object.new | |
factory :post do | |
initialize_with { new(**attributes.reject { _2 in NIL_TITLE | NIL_BODY }) } # reject sentinels when initializing | |
title { NIL_TITLE } | |
body { NIL_BODY } | |
end | |
end | |
class FactoryBotTest < Minitest::Test | |
def test_create | |
post = FactoryBot.create(:post) | |
assert_nil post.title | |
end | |
def test_build | |
post = FactoryBot.build(:post) | |
assert_nil post.title | |
end | |
def test_attributes_for | |
post = FactoryBot.attributes_for(:post) | |
assert_nil post[:title] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment