repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/spec/support/models/artificial_blog.rb
spec/support/models/artificial_blog.rb
# frozen_string_literal: true class ArtificialBlog < Blog def self.policy_class BlogPolicy end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/spec/support/models/customer/post.rb
spec/support/models/customer/post.rb
# frozen_string_literal: true module Customer class Post < ::Post extend ActiveModel::Naming def self.policy_class PostPolicy end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/spec/support/models/project_one_two_three/avatar_four_five_six.rb
spec/support/models/project_one_two_three/avatar_four_five_six.rb
# frozen_string_literal: true module ProjectOneTwoThree class AvatarFourFiveSix extend ActiveModel::Naming end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/spec/support/models/project_one_two_three/tag_four_five_six.rb
spec/support/models/project_one_two_three/tag_four_five_six.rb
# frozen_string_literal: true module ProjectOneTwoThree class TagFourFiveSix def initialize(user) @user = user end attr_reader(:user) end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/spec/support/lib/custom_cache.rb
spec/support/lib/custom_cache.rb
# frozen_string_literal: true class CustomCache def initialize @store = {} end def to_h @store end def [](key) @store[key] end def []=(key, value) @store[key] = value end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/spec/support/lib/instance_tracking.rb
spec/support/lib/instance_tracking.rb
# frozen_string_literal: true module InstanceTracking module ClassMethods def instances @instances || 0 end attr_writer :instances end def self.prepended(other) other.extend(ClassMethods) end def initialize(*args, **kwargs, &block) self.class.instances += 1 super(*args, **kwargs, &block) end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/spec/support/lib/controller.rb
spec/support/lib/controller.rb
# frozen_string_literal: true class Controller attr_accessor :current_user attr_reader :action_name, :params class View def initialize(controller) @controller = controller end attr_reader :controller end class << self def helper(mod) View.include(mod) end def helper_method(method) View.class_eval <<-RUBY, __FILE__, __LINE__ + 1 def #{method}(*args, **kwargs, &block) controller.send(:#{method}, *args, **kwargs, &block) end RUBY end end include Pundit::Authorization # Mark protected methods public so they may be called in test public(*Pundit::Authorization.protected_instance_methods) def initialize(current_user, action_name, params) @current_user = current_user @action_name = action_name @params = params end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/spec/policies/post_policy_spec.rb
spec/policies/post_policy_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe PostPolicy do let(:user) { double } let(:own_post) { double(user: user) } let(:other_post) { double(user: double) } subject { described_class } permissions :update?, :show? do it "is successful when all permissions match" do should permit(user, own_post) end it "fails when any permissions do not match" do expect do should permit(user, other_post) end.to raise_error(RSpec::Expectations::ExpectationNotMetError) end it "uses the default description if not overridden" do expect(permit(user, own_post).description).to eq("permit #{user.inspect} and #{own_post.inspect}") end context "when the matcher description is overridden" do after do Pundit::RSpec::Matchers.description = nil end it "sets a custom matcher description with a Proc" do allow(user).to receive(:role).and_return("default_role") allow(own_post).to receive(:id).and_return(1) Pundit::RSpec::Matchers.description = lambda { |user, record| "permit user with role #{user.role} to access record with ID #{record.id}" } description = permit(user, own_post).description expect(description).to eq("permit user with role default_role to access record with ID 1") end it "sets a custom matcher description with a string" do Pundit::RSpec::Matchers.description = "permit user" expect(permit(user, own_post).description).to eq("permit user") end end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/spec/pundit/helper_spec.rb
spec/pundit/helper_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe Pundit::Helper do let(:user) { double } let(:controller) { Controller.new(user, "update", double) } let(:view) { Controller::View.new(controller) } describe "#policy_scope" do it "doesn't flip pundit_policy_scoped?" do scoped = view.policy_scope(Post) expect(scoped).to be(Post.published) expect(controller).not_to be_pundit_policy_scoped end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/pundit.rb
lib/pundit.rb
# frozen_string_literal: true require "active_support" require "pundit/version" require "pundit/error" require "pundit/policy_finder" require "pundit/context" require "pundit/authorization" require "pundit/helper" require "pundit/cache_store" require "pundit/cache_store/null_store" require "pundit/cache_store/legacy_store" require "pundit/railtie" if defined?(Rails) # Hello? Yes, this is Pundit. # # @api public module Pundit # @api private # @since v1.0.0 # @deprecated See {Pundit::PolicyFinder} SUFFIX = Pundit::PolicyFinder::SUFFIX # @api private # @private # @since v0.1.0 module Generators; end def self.included(base) location = caller_locations(1, 1).first warn <<~WARNING 'include Pundit' is deprecated. Please use 'include Pundit::Authorization' instead. (called from #{location.label} at #{location.path}:#{location.lineno}) WARNING base.include Authorization end class << self # @see Pundit::Context#authorize # @since v1.0.0 def authorize(user, record, query, policy_class: nil, cache: nil) context = if cache policy_cache = CacheStore::LegacyStore.new(cache) Context.new(user: user, policy_cache: policy_cache) else Context.new(user: user) end context.authorize(record, query: query, policy_class: policy_class) end # @see Pundit::Context#policy_scope # @since v0.1.0 def policy_scope(user, *args, **kwargs, &block) Context.new(user: user).policy_scope(*args, **kwargs, &block) end # @see Pundit::Context#policy_scope! # @since v0.1.0 def policy_scope!(user, *args, **kwargs, &block) Context.new(user: user).policy_scope!(*args, **kwargs, &block) end # @see Pundit::Context#policy # @since v0.1.0 def policy(user, *args, **kwargs, &block) Context.new(user: user).policy(*args, **kwargs, &block) end # @see Pundit::Context#policy! # @since v0.1.0 def policy!(user, *args, **kwargs, &block) Context.new(user: user).policy!(*args, **kwargs, &block) end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/generators/rspec/policy_generator.rb
lib/generators/rspec/policy_generator.rb
# frozen_string_literal: true # @private module Rspec # @private module Generators # @private class PolicyGenerator < ::Rails::Generators::NamedBase source_root File.expand_path("templates", __dir__) def create_policy_spec template "policy_spec.rb.tt", File.join("spec/policies", class_path, "#{file_name}_policy_spec.rb") end end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/generators/pundit/install/install_generator.rb
lib/generators/pundit/install/install_generator.rb
# frozen_string_literal: true module Pundit # @private module Generators # @private class InstallGenerator < ::Rails::Generators::Base source_root File.expand_path("templates", __dir__) def copy_application_policy template "application_policy.rb.tt", "app/policies/application_policy.rb" end end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/generators/pundit/policy/policy_generator.rb
lib/generators/pundit/policy/policy_generator.rb
# frozen_string_literal: true module Pundit # @private module Generators # @private class PolicyGenerator < ::Rails::Generators::NamedBase source_root File.expand_path("templates", __dir__) def create_policy template "policy.rb.tt", File.join("app/policies", class_path, "#{file_name}_policy.rb") end hook_for :test_framework end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/generators/test_unit/policy_generator.rb
lib/generators/test_unit/policy_generator.rb
# frozen_string_literal: true # @private module TestUnit # @private module Generators # @private class PolicyGenerator < ::Rails::Generators::NamedBase source_root File.expand_path("templates", __dir__) def create_policy_test template "policy_test.rb.tt", File.join("test/policies", class_path, "#{file_name}_policy_test.rb") end end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/pundit/cache_store.rb
lib/pundit/cache_store.rb
# frozen_string_literal: true module Pundit # Namespace for cache store implementations. # # Cache stores are used to cache policy lookups, so you get the same policy # instance for the same record. # @since v2.3.2 module CacheStore # @!group Cache Store Interface # @!method fetch(user:, record:, &block) # Looks up a stored policy or generate a new one. # # @since v2.3.2 # @note This is a method template, but the method does not exist in this module. # @param user [Object] the user that initiated the action # @param record [Object] the object being accessed # @param block [Proc] the block to execute if missing # @return [Object] the policy # @!endgroup end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/pundit/version.rb
lib/pundit/version.rb
# frozen_string_literal: true module Pundit # The current version of Pundit. VERSION = "2.5.2" end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/pundit/railtie.rb
lib/pundit/railtie.rb
# frozen_string_literal: true module Pundit # @since v2.5.0 class Railtie < Rails::Railtie if Rails.version.to_f >= 8.0 initializer "pundit.stats_directories" do require "rails/code_statistics" if Rails.root.join("app/policies").directory? Rails::CodeStatistics.register_directory("Policies", "app/policies") end if Rails.root.join("test/policies").directory? Rails::CodeStatistics.register_directory("Policy tests", "test/policies", test_directory: true) end end end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/pundit/rspec.rb
lib/pundit/rspec.rb
# frozen_string_literal: true require "pundit" # Array#to_sentence require "active_support/core_ext/array/conversions" module Pundit # Namespace for Pundit's RSpec integration. # @since v0.1.0 module RSpec # Namespace for Pundit's RSpec matchers. module Matchers extend ::RSpec::Matchers::DSL # @!method description=(description) class << self # Used to build a suitable description for the Pundit `permit` matcher. # @api public # @param value [String, Proc] # @example # Pundit::RSpec::Matchers.description = ->(user, record) do # "permit user with role #{user.role} to access record with ID #{record.id}" # end attr_writer :description # Used to retrieve a suitable description for the Pundit `permit` matcher. # @api private # @private def description(user, record) return @description.call(user, record) if defined?(@description) && @description.respond_to?(:call) @description end end # rubocop:disable Metrics/BlockLength matcher :permit do |user, record| match_proc = lambda do |policy| @violating_permissions = permissions.find_all do |permission| !policy.new(user, record).public_send(permission) end @violating_permissions.empty? end match_when_negated_proc = lambda do |policy| @violating_permissions = permissions.find_all do |permission| policy.new(user, record).public_send(permission) end @violating_permissions.empty? end failure_message_proc = lambda do |policy| "Expected #{policy} to grant #{permissions.to_sentence} on " \ "#{record} but #{@violating_permissions.to_sentence} #{was_or_were} not granted" end failure_message_when_negated_proc = lambda do |policy| "Expected #{policy} not to grant #{permissions.to_sentence} on " \ "#{record} but #{@violating_permissions.to_sentence} #{was_or_were} granted" end def was_or_were if @violating_permissions.count > 1 "were" else "was" end end description do Pundit::RSpec::Matchers.description(user, record) || super() end if respond_to?(:match_when_negated) match(&match_proc) match_when_negated(&match_when_negated_proc) failure_message(&failure_message_proc) failure_message_when_negated(&failure_message_when_negated_proc) else # :nocov: # Compatibility with RSpec < 3.0, released 2014-06-01. match_for_should(&match_proc) match_for_should_not(&match_when_negated_proc) failure_message_for_should(&failure_message_proc) failure_message_for_should_not(&failure_message_when_negated_proc) # :nocov: end if ::RSpec.respond_to?(:current_example) def current_example ::RSpec.current_example end else # :nocov: # Compatibility with RSpec < 3.0, released 2014-06-01. def current_example example end # :nocov: end def permissions current_example.metadata.fetch(:permissions) do raise KeyError, <<~ERROR.strip No permissions in example metadata, did you forget to wrap with `permissions :show?, ...`? ERROR end end end # rubocop:enable Metrics/BlockLength end # Mixed in to all policy example groups to provide a DSL. module DSL # @example # describe PostPolicy do # permissions :show?, :update? do # it { is_expected.to permit(user, own_post) } # end # end # # @example focused example group # describe PostPolicy do # permissions :show?, :update?, :focus do # it { is_expected.to permit(user, own_post) } # end # end # # @param list [Symbol, Array<Symbol>] a permission to describe # @return [void] def permissions(*list, &block) metadata = { permissions: list, caller: caller } if list.last == :focus list.pop metadata[:focus] = true end description = list.to_sentence describe(description, metadata) { instance_eval(&block) } end end # Mixed in to all policy example groups. # # @private not useful module PolicyExampleGroup include Pundit::RSpec::Matchers def self.included(base) base.metadata[:type] = :policy base.extend Pundit::RSpec::DSL super end end end end RSpec.configure do |config| config.include( Pundit::RSpec::PolicyExampleGroup, type: :policy, file_path: %r{spec/policies} ) end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/pundit/helper.rb
lib/pundit/helper.rb
# frozen_string_literal: true module Pundit # Rails view helpers, to allow a slightly different view-specific # implementation of the methods in {Pundit::Authorization}. # # @api private # @since v1.0.0 module Helper # @see Pundit::Authorization#pundit_policy_scope # @since v1.0.0 def policy_scope(scope) pundit_policy_scope(scope) end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/pundit/policy_finder.rb
lib/pundit/policy_finder.rb
# frozen_string_literal: true # String#safe_constantize, String#demodulize, String#underscore, String#camelize require "active_support/core_ext/string/inflections" module Pundit # Finds policy and scope classes for given object. # @since v0.1.0 # @api public # @example # user = User.find(params[:id]) # finder = PolicyFinder.new(user) # finder.policy #=> UserPolicy # finder.scope #=> UserPolicy::Scope # class PolicyFinder # A constant applied to the end of the class name to find the policy class. # # @api private # @since v2.5.0 SUFFIX = "Policy" # @see #initialize # @since v0.1.0 attr_reader :object # @param object [any] the object to find policy and scope classes for # @since v0.1.0 def initialize(object) @object = object end # @return [nil, Scope{#resolve}] scope class which can resolve to a scope # @see https://github.com/varvet/pundit#scopes # @example # scope = finder.scope #=> UserPolicy::Scope # scope.resolve #=> <#ActiveRecord::Relation ...> # # @since v0.1.0 def scope "#{policy}::Scope".safe_constantize end # @return [nil, Class] policy class with query methods # @see https://github.com/varvet/pundit#policies # @example # policy = finder.policy #=> UserPolicy # policy.show? #=> true # policy.update? #=> false # # @since v0.1.0 def policy klass = find(object) klass.is_a?(String) ? klass.safe_constantize : klass end # @return [Scope{#resolve}] scope class which can resolve to a scope # @raise [NotDefinedError] if scope could not be determined # # @since v0.1.0 def scope! scope or raise NotDefinedError, "unable to find scope `#{find(object)}::Scope` for `#{object.inspect}`" end # @return [Class] policy class with query methods # @raise [NotDefinedError] if policy could not be determined # # @since v0.1.0 def policy! policy or raise NotDefinedError, "unable to find policy `#{find(object)}` for `#{object.inspect}`" end # @return [String] the name of the key this object would have in a params hash # # @since v1.1.0 def param_key # rubocop:disable Metrics/AbcSize model = object.is_a?(Array) ? object.last : object if model.respond_to?(:model_name) model.model_name.param_key.to_s elsif model.is_a?(Class) model.to_s.demodulize.underscore else model.class.to_s.demodulize.underscore end end private # Given an object, find the policy class name. # # Uses recursion to handle namespaces. # # @return [String, Class] the policy class, or its name. # @since v0.2.0 def find(subject) if subject.is_a?(Array) modules = subject.dup last = modules.pop context = modules.map { |x| find_class_name(x) }.join("::") [context, find(last)].join("::") elsif subject.respond_to?(:policy_class) subject.policy_class elsif subject.class.respond_to?(:policy_class) subject.class.policy_class else klass = find_class_name(subject) "#{klass}#{SUFFIX}" end end # Given an object, find its' class name. # # - Supports ActiveModel. # - Supports regular classes. # - Supports symbols. # - Supports object instances. # # @return [String, Class] the class, or its name. # @since v1.1.0 def find_class_name(subject) if subject.respond_to?(:model_name) subject.model_name elsif subject.class.respond_to?(:model_name) subject.class.model_name elsif subject.is_a?(Class) subject elsif subject.is_a?(Symbol) subject.to_s.camelize else subject.class end end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/pundit/context.rb
lib/pundit/context.rb
# frozen_string_literal: true module Pundit # {Pundit::Context} is intended to be created once per request and user, and # it is then used to perform authorization checks throughout the request. # # @example Using Sinatra # helpers do # def current_user = ... # # def pundit # @pundit ||= Pundit::Context.new(user: current_user) # end # end # # get "/posts/:id" do |id| # pundit.authorize(Post.find(id), query: :show?) # end # # @example Using [Roda](https://roda.jeremyevans.net/index.html) # route do |r| # context = Pundit::Context.new(user:) # # r.get "posts", Integer do |id| # context.authorize(Post.find(id), query: :show?) # end # end # # @since v2.3.2 class Context # @see Pundit::Authorization#pundit # @param user later passed to policies and scopes # @param policy_cache [#fetch] cache store for policies (see e.g. {CacheStore::NullStore}) # @since v2.3.2 def initialize(user:, policy_cache: CacheStore::NullStore.instance) @user = user @policy_cache = policy_cache end # @api public # @see #initialize # @since v2.3.2 attr_reader :user # @api private # @see #initialize # @since v2.3.2 attr_reader :policy_cache # @!group Policies # Retrieves the policy for the given record, initializing it with the # record and user and finally throwing an error if the user is not # authorized to perform the given action. # # @param possibly_namespaced_record [Object, Array] the object we're checking permissions of # @param query [Symbol, String] the predicate method to check on the policy (e.g. `:show?`) # @param policy_class [Class] the policy class we want to force use of # @raise [NotAuthorizedError] if the given query method returned false # @return [Object] Always returns the passed object record # @since v2.3.2 def authorize(possibly_namespaced_record, query:, policy_class:) record = pundit_model(possibly_namespaced_record) policy = if policy_class policy_class.new(user, record) else policy!(possibly_namespaced_record) end raise NotAuthorizedError, query: query, record: record, policy: policy unless policy.public_send(query) record end # Retrieves the policy for the given record. # # @see https://github.com/varvet/pundit#policies # @param record [Object] the object we're retrieving the policy for # @raise [InvalidConstructorError] if the policy constructor called incorrectly # @return [Object, nil] instance of policy class with query methods # @since v2.3.2 def policy(record) cached_find(record, &:policy) end # Retrieves the policy for the given record, or raises if not found. # # @see https://github.com/varvet/pundit#policies # @param record [Object] the object we're retrieving the policy for # @raise [NotDefinedError] if the policy cannot be found # @raise [InvalidConstructorError] if the policy constructor called incorrectly # @return [Object] instance of policy class with query methods # @since v2.3.2 def policy!(record) cached_find(record, &:policy!) end # @!endgroup # @!group Scopes # Retrieves the policy scope for the given record. # # @see https://github.com/varvet/pundit#scopes # @param scope [Object] the object we're retrieving the policy scope for # @raise [InvalidConstructorError] if the policy constructor called incorrectly # @return [Scope{#resolve}, nil] instance of scope class which can resolve to a scope # @since v2.3.2 def policy_scope(scope) policy_scope_class = policy_finder(scope).scope return unless policy_scope_class begin policy_scope = policy_scope_class.new(user, pundit_model(scope)) rescue ArgumentError raise InvalidConstructorError, "Invalid #<#{policy_scope_class}> constructor is called" end policy_scope.resolve end # Retrieves the policy scope for the given record. Raises if not found. # # @see https://github.com/varvet/pundit#scopes # @param scope [Object] the object we're retrieving the policy scope for # @raise [NotDefinedError] if the policy scope cannot be found # @raise [InvalidConstructorError] if the policy constructor called incorrectly # @return [Scope{#resolve}] instance of scope class which can resolve to a scope # @since v2.3.2 def policy_scope!(scope) policy_scope_class = policy_finder(scope).scope! begin policy_scope = policy_scope_class.new(user, pundit_model(scope)) rescue ArgumentError raise InvalidConstructorError, "Invalid #<#{policy_scope_class}> constructor is called" end policy_scope.resolve end # @!endgroup private # @!group Private Helpers # Finds a cached policy for the given record, or yields to find one. # # @api private # @param record [Object] the object we're retrieving the policy for # @yield a policy finder if no policy was cached # @yieldparam [PolicyFinder] policy_finder # @yieldreturn [#new(user, model)] # @return [Policy, nil] an instantiated policy # @raise [InvalidConstructorError] if policy can't be instantated # @since v2.3.2 def cached_find(record) policy_cache.fetch(user: user, record: record) do klass = yield policy_finder(record) next unless klass model = pundit_model(record) begin klass.new(user, model) rescue ArgumentError raise InvalidConstructorError, "Invalid #<#{klass}> constructor is called" end end end # Return a policy finder for the given record. # # @api private # @return [PolicyFinder] # @since v2.3.2 def policy_finder(record) PolicyFinder.new(record) end # Given a possibly namespaced record, return the actual record. # # @api private # @since v2.3.2 def pundit_model(record) record.is_a?(Array) ? record.last : record end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/pundit/authorization.rb
lib/pundit/authorization.rb
# frozen_string_literal: true module Pundit # Pundit DSL to include in your controllers to provide authorization helpers. # # @example # class ApplicationController < ActionController::Base # include Pundit::Authorization # end # @see #pundit # @api public # @since v2.2.0 module Authorization extend ActiveSupport::Concern included do helper Helper if respond_to?(:helper) if respond_to?(:helper_method) helper_method :policy helper_method :pundit_policy_scope helper_method :pundit_user end end protected # An instance of {Pundit::Context} initialized with the current user. # # @note this method is memoized and will return the same instance during the request. # @api public # @return [Pundit::Context] # @see #pundit_user # @see #policies # @since v2.3.2 def pundit @pundit ||= Pundit::Context.new( user: pundit_user, policy_cache: Pundit::CacheStore::LegacyStore.new(policies) ) end # Hook method which allows customizing which user is passed to policies and # scopes initialized by {#authorize}, {#policy} and {#policy_scope}. # # @note Make sure to call `pundit_reset!` if this changes during a request. # @see https://github.com/varvet/pundit#customize-pundit-user # @see #pundit # @see #pundit_reset! # @return [Object] the user object to be used with pundit # @since v0.2.2 def pundit_user current_user end # Clears the cached Pundit authorization data. # # This method should be called when the pundit_user is changed, # such as during user switching, to ensure that stale authorization # data is not used. Pundit caches authorization policies and scopes # for the pundit_user, so calling this method will reset those # caches and ensure that the next authorization checks are performed # with the correct context for the new pundit_user. # # @return [void] # @since v2.5.0 def pundit_reset! @pundit = nil @_pundit_policies = nil @_pundit_policy_scopes = nil @_pundit_policy_authorized = nil @_pundit_policy_scoped = nil end # @!group Policies # Retrieves the policy for the given record, initializing it with the record # and current user and finally throwing an error if the user is not # authorized to perform the given action. # # @param record [Object, Array] the object we're checking permissions of # @param query [Symbol, String] the predicate method to check on the policy (e.g. `:show?`). # If omitted then this defaults to the Rails controller action name. # @param policy_class [Class] the policy class we want to force use of # @raise [NotAuthorizedError] if the given query method returned false # @return [record] Always returns the passed object record # @see Pundit::Context#authorize # @see #verify_authorized # @since v0.1.0 def authorize(record, query = nil, policy_class: nil) query ||= "#{action_name}?" @_pundit_policy_authorized = true pundit.authorize(record, query: query, policy_class: policy_class) end # Allow this action not to perform authorization. # # @see https://github.com/varvet/pundit#ensuring-policies-and-scopes-are-used # @return [void] # @see #verify_authorized # @since v1.0.0 def skip_authorization @_pundit_policy_authorized = :skipped end # @return [Boolean] wether or not authorization has been performed # @see #authorize # @see #skip_authorization # @since v1.0.0 def pundit_policy_authorized? !!@_pundit_policy_authorized end # Raises an error if authorization has not been performed. # # Usually used as an `after_action` filter to prevent programmer error in # forgetting to call {#authorize} or {#skip_authorization}. # # @see https://github.com/varvet/pundit#ensuring-policies-and-scopes-are-used # @raise [AuthorizationNotPerformedError] if authorization has not been performed # @return [void] # @see #authorize # @see #skip_authorization # @since v0.1.0 def verify_authorized raise AuthorizationNotPerformedError, self.class unless pundit_policy_authorized? end # rubocop:disable Naming/MemoizedInstanceVariableName # Cache of policies. You should not rely on this method. # # @api private # @since v1.0.0 def policies @_pundit_policies ||= {} end # rubocop:enable Naming/MemoizedInstanceVariableName # @!endgroup # Retrieves the policy for the given record. # # @see https://github.com/varvet/pundit#policies # @param record [Object] the object we're retrieving the policy for # @return [Object] instance of policy class with query methods # @since v0.1.0 def policy(record) pundit.policy!(record) end # @!group Policy Scopes # Retrieves the policy scope for the given record. # # @see https://github.com/varvet/pundit#scopes # @param scope [Object] the object we're retrieving the policy scope for # @param policy_scope_class [#resolve] the policy scope class we want to force use of # @return [#resolve, nil] instance of scope class which can resolve to a scope # @since v0.1.0 def policy_scope(scope, policy_scope_class: nil) @_pundit_policy_scoped = true policy_scope_class ? policy_scope_class.new(pundit_user, scope).resolve : pundit_policy_scope(scope) end # Allow this action not to perform policy scoping. # # @see https://github.com/varvet/pundit#ensuring-policies-and-scopes-are-used # @return [void] # @see #verify_policy_scoped # @since v1.0.0 def skip_policy_scope @_pundit_policy_scoped = :skipped end # @return [Boolean] wether or not policy scoping has been performed # @see #policy_scope # @see #skip_policy_scope # @since v1.0.0 def pundit_policy_scoped? !!@_pundit_policy_scoped end # Raises an error if policy scoping has not been performed. # # Usually used as an `after_action` filter to prevent programmer error in # forgetting to call {#policy_scope} or {#skip_policy_scope} in index # actions. # # @see https://github.com/varvet/pundit#ensuring-policies-and-scopes-are-used # @raise [AuthorizationNotPerformedError] if policy scoping has not been performed # @return [void] # @see #policy_scope # @see #skip_policy_scope # @since v0.2.1 def verify_policy_scoped raise PolicyScopingNotPerformedError, self.class unless pundit_policy_scoped? end # rubocop:disable Naming/MemoizedInstanceVariableName # Cache of policy scope. You should not rely on this method. # # @api private # @since v1.0.0 def policy_scopes @_pundit_policy_scopes ||= {} end # rubocop:enable Naming/MemoizedInstanceVariableName # This was added to allow calling `policy_scope!` without flipping the # `pundit_policy_scoped?` flag. # # It's used internally by `policy_scope`, as well as from the views # when they call `policy_scope`. It works because views get their helper # from {Pundit::Helper}. # # @note This also memoizes the instance with `scope` as the key. # @see Pundit::Helper#policy_scope # @api private # @since v1.0.0 def pundit_policy_scope(scope) policy_scopes[scope] ||= pundit.policy_scope!(scope) end private :pundit_policy_scope # @!endgroup # @!group Strong Parameters # Retrieves a set of permitted attributes from the policy. # # Done by instantiating the policy class for the given record and calling # `permitted_attributes` on it, or `permitted_attributes_for_{action}` if # `action` is defined. It then infers what key the record should have in the # params hash and retrieves the permitted attributes from the params hash # under that key. # # @see https://github.com/varvet/pundit#strong-parameters # @param record [Object] the object we're retrieving permitted attributes for # @param action [Symbol, String] the name of the action being performed on the record (e.g. `:update`). # If omitted then this defaults to the Rails controller action name. # @return [Hash{String => Object}] the permitted attributes # @since v1.0.0 def permitted_attributes(record, action = action_name) policy = policy(record) method_name = if policy.respond_to?("permitted_attributes_for_#{action}") "permitted_attributes_for_#{action}" else "permitted_attributes" end pundit_params_for(record).permit(*policy.public_send(method_name)) end # Retrieves the params for the given record. # # @param record [Object] the object we're retrieving params for # @return [ActionController::Parameters] the params # @since v2.0.0 def pundit_params_for(record) params.require(PolicyFinder.new(record).param_key) end # @!endgroup end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/pundit/error.rb
lib/pundit/error.rb
# frozen_string_literal: true module Pundit # @api private # @since v1.0.0 # To avoid name clashes with common Error naming when mixing in Pundit, # keep it here with compact class style definition. class Error < StandardError; end # Error that will be raised when authorization has failed # @since v0.1.0 class NotAuthorizedError < Error # @see #initialize # @since v0.2.3 attr_reader :query # @see #initialize # @since v0.2.3 attr_reader :record # @see #initialize # @since v0.2.3 attr_reader :policy # @since v1.0.0 # # @overload initialize(message) # Create an error with a simple error message. # @param [String] message A simple error message string. # # @overload initialize(options) # Create an error with the specified attributes. # @param [Hash] options The error options. # @option options [String] :message Optional custom error message. Will default to a generalized message. # @option options [Symbol] :query The name of the policy method that was checked. # @option options [Object] :record The object that was being checked with the policy. # @option options [Class] :policy The class of policy that was used for the check. def initialize(options = {}) if options.is_a? String message = options else @query = options[:query] @record = options[:record] @policy = options[:policy] message = options.fetch(:message) do record_name = record.is_a?(Class) ? record.to_s : "this #{record.class}" "not allowed to #{policy.class}##{query} #{record_name}" end end super(message) end end # Error that will be raised if a policy or policy scope constructor is not called correctly. # @since v2.0.0 class InvalidConstructorError < Error; end # Error that will be raised if a controller action has not called the # `authorize` or `skip_authorization` methods. # @since v0.2.3 class AuthorizationNotPerformedError < Error; end # Error that will be raised if a controller action has not called the # `policy_scope` or `skip_policy_scope` methods. # @since v0.3.0 class PolicyScopingNotPerformedError < AuthorizationNotPerformedError; end # Error that will be raised if a policy or policy scope is not defined. # @since v0.1.0 class NotDefinedError < Error; end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/pundit/cache_store/null_store.rb
lib/pundit/cache_store/null_store.rb
# frozen_string_literal: true module Pundit module CacheStore # A cache store that does not cache anything. # # Use `NullStore.instance` to get the singleton instance, it is thread-safe. # # @see Pundit::Context#initialize # @api private # @since v2.3.2 class NullStore @instance = new class << self # @since v2.3.2 # @return [NullStore] the singleton instance attr_reader :instance end # Always yields, does not cache anything. # @yield # @return [any] whatever the block returns. # @since v2.3.2 def fetch(*, **) yield end end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
varvet/pundit
https://github.com/varvet/pundit/blob/3488802b2f218ba26562e91186655297c95eb6da/lib/pundit/cache_store/legacy_store.rb
lib/pundit/cache_store/legacy_store.rb
# frozen_string_literal: true module Pundit module CacheStore # A cache store that uses only the record as a cache key, and ignores the user. # # The original cache mechanism used by Pundit. # # @api private # @since v2.3.2 class LegacyStore # @since v2.3.2 def initialize(hash = {}) @store = hash end # A cache store that uses only the record as a cache key, and ignores the user. # # @note `nil` results are not cached. # @since v2.3.2 def fetch(user:, record:) _ = user @store[record] ||= yield end end end end
ruby
MIT
3488802b2f218ba26562e91186655297c95eb6da
2026-01-04T15:38:58.048292Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/features/support/env.rb
features/support/env.rb
require "aruba/cucumber"
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/features/support/bourbon_support.rb
features/support/bourbon_support.rb
module BourbonSupport def install_bourbon(path = nil) if path run_simple("bundle exec bourbon install --path '#{path}'") else run_simple("bundle exec bourbon install") end end def bourbon_path(prefix, path) if prefix File.join(prefix, 'bourbon', path) else File.join('bourbon', path) end end end World(BourbonSupport)
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/features/step_definitions/bourbon_steps.rb
features/step_definitions/bourbon_steps.rb
Given /^bourbon is already installed$/ do install_bourbon end Given /^I install bourbon to "([^"]*)"$/ do |path| end Then /^the sass directories(?: with "([^"]+)" prefix)? should have been generated$/ do |prefix| sass_directories = [ "bourbon/helpers", "bourbon/library", "bourbon/settings", "bourbon/utilities", "bourbon/validators", ] sass_directories.map!{ |directory| bourbon_path(prefix, directory) } sass_directories.each do |sass_directory| expect(sass_directory).to be_an_existing_directory end end Then /^the master bourbon partial should have been generated(?: within "([^"]+)" directory)?$/ do |prefix| expect(bourbon_path(prefix, "_bourbon.scss")).to be_an_existing_file end Then /^bourbon should not have been generated$/ do expect("bourbon").not_to be_an_existing_directory end Then /^the output should contain the current version of Bourbon$/ do expect(last_command_started).to have_output "Bourbon #{Bourbon::VERSION}" end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/spec_helper.rb
spec/spec_helper.rb
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib")) $LOAD_PATH.unshift(File.dirname(__FILE__)) require "rspec" require "bourbon" require "aruba/api" require "css_parser" Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } RSpec.configure do |config| config.include SassSupport config.include CssParser config.include ParserSupport config.include Aruba::Api config.before(:all) do generate_css end config.after(:all) do clean_up end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/support/parser_support.rb
spec/support/parser_support.rb
module ParserSupport def self.parser @parser ||= CssParser::Parser.new end def self.parse_file(identifier) parser.load_file!("tmp/#{identifier}.css") end def self.show_contents(identifier) css_file_contents = File.open("tmp/#{identifier}.css").read css_file_contents.each_line do |line| puts line end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/support/sass_support.rb
spec/support/sass_support.rb
module SassSupport def generate_css FileUtils.mkdir("tmp") `sass -I . spec/fixtures:tmp --update --precision=5 --sourcemap=none` end def clean_up FileUtils.rm_rf("tmp") end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/support/matchers/have_rule.rb
spec/support/matchers/have_rule.rb
RSpec::Matchers.define :have_rule do |expected| match do |selector| @rules = rules_from_selector(selector) @rules.include? expected end failure_message do |selector| if @rules.empty? %{no CSS for selector #{selector} were found} else rules = @rules.join("; ") %{Expected selector #{selector} to have CSS rule "#{expected}". Had "#{rules}".} end end def rules_from_selector(selector) rulesets = ParserSupport.parser.find_by_selector(selector) if rulesets.empty? [] else rules(rulesets) end end def rules(rulesets) rules = [] rulesets.map do |ruleset| ruleset.split(";").each do |rule| rules << rule.strip end end rules end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/support/matchers/have_value.rb
spec/support/matchers/have_value.rb
RSpec::Matchers.define :have_value do |expected| match do |variable| selector_class = variable.sub("$", ".") @value_attribute = ParserSupport.parser.find_by_selector(selector_class)[0] unless @value_attribute.nil? actual_value = @value_attribute.split(":")[1].strip.sub(";", "") actual_value == expected end end failure_message do |variable_name| value_attribute = @value_attribute.to_s %{Expected variable #{variable_name} to have value "#{expected}". Had "#{value_attribute}".} end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/support/matchers/have_ruleset.rb
spec/support/matchers/have_ruleset.rb
RSpec::Matchers.define :have_ruleset do |expected| match do |selector| @ruleset = rules_from_selector(selector) @ruleset.join("; ") == expected end failure_message do |selector| if @ruleset.empty? %{no CSS for selector #{selector} were found} else ruleset = @ruleset.join("; ") %{Expected selector #{selector} to have CSS rule "#{expected}". Had "#{ruleset}".} end end def rules_from_selector(selector) ParserSupport.parser.find_by_selector(selector) end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/validators/contains_spec.rb
spec/bourbon/validators/contains_spec.rb
require "spec_helper" describe "contains" do before(:all) do ParserSupport.parse_file("validators/contains") end context "called on array with single item" do it "contains item" do expect(".single").to have_rule("color: #fff") end it "doesn't contain missing item" do expect(".single-missing").to have_rule("color: #000") end end context "called with array with multiple items" do it "contains item" do expect(".multiple").to have_rule("color: #fff") end it "doesn't contain missing item" do expect(".multiple-missing").to have_rule("color: #000") end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/validators/is_length_spec.rb
spec/bourbon/validators/is_length_spec.rb
require "spec_helper" describe "is-length" do before(:all) do ParserSupport.parse_file("validators/is-length") end context "checks if unitless integer can be represented as a length" do it "returns false" do expect(".integer").not_to have_rule("color: #fff") end end context "checks if px can be represented as a length" do it "returns true" do expect(".pixels").to have_rule("color: #fff") end end context "checks if em can be represented as a length" do it "returns true" do expect(".ems").to have_rule("color: #fff") end end context "checks if percent can be represented as a length" do it "returns true" do expect(".percent").to have_rule("color: #fff") end end context "parses calculated values" do it "returns true" do expect(".calc").to have_rule("color: #fff") end end context "parses custom properties" do it "returns true" do expect(".var").to have_rule("color: #fff") end end context "parses environment variables" do it "returns true" do expect(".env").to have_rule("color: #fff") end end context "checks if strings can be represented as a length" do it "returns false" do expect(".string").not_to have_rule("color: #fff") end end context "checks if null can be represented as a length" do it "returns false" do expect(".null").not_to have_rule("color: #fff") end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/validators/is_number_spec.rb
spec/bourbon/validators/is_number_spec.rb
require "spec_helper" describe "is-number" do before(:all) do ParserSupport.parse_file("validators/is-number") end context "called with integer" do it "is a number" do expect(".integer").to have_rule("line-height: 1") end end context "called with px" do it "is a number" do expect(".px").to have_rule("line-height: 2px") end end context "called with em" do it "is a number" do expect(".em").to have_rule("line-height: 3em") end end context "called with rem" do it "is a number" do expect(".rem").to have_rule("line-height: 4rem") end end context "called with percent" do it "is a number" do expect(".percent").to have_rule("line-height: 5%") end end context "called with string" do it "is not a number" do expect(".string").to_not have_rule("line-height: \"stringy\"") end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/validators/is_size_spec.rb
spec/bourbon/validators/is_size_spec.rb
require "spec_helper" describe "is-size" do before(:all) do ParserSupport.parse_file("validators/is-size") end context "called with integer" do it "is not a size" do expect(".integer").to_not have_rule("margin-top: 1") end end context "called with px" do it "is a size" do expect(".px").to have_rule("margin-top: 2px") end end context "called with em" do it "is a size" do expect(".em").to have_rule("margin-top: 3em") end end context "called with rem" do it "is a size" do expect(".rem").to have_rule("margin-top: 4rem") end end context "called with percent" do it "is a size" do expect(".percent").to have_rule("margin-top: 5%") end end context "called with string" do it "is not a size" do expect(".string").to_not have_rule("margin-top: \"stringy\"") end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/padding_spec.rb
spec/bourbon/library/padding_spec.rb
require "spec_helper" describe "padding" do before(:all) do ParserSupport.parse_file("library/padding") end context "called with one size" do it "applies same width to all sides" do rule = "padding: 1px" expect(".padding-all").to have_rule(rule) end end context "called with two sizes" do it "applies to alternating sides" do rule = "padding: 2px 3px" expect(".padding-alternate").to have_rule(rule) end end context "called with three sizes" do it "applies second width to left and right" do rule = "padding: 4px 5px 6px" expect(".padding-implied-left").to have_rule(rule) end end context "called with four sizes" do it "applies different widths to all sides" do rule = "padding: 7px 8px 9px 10px" expect(".padding-explicit").to have_rule(rule) end end context "called with null values" do it "writes rules for other three" do ruleset = "padding-top: 11px; " + "padding-right: 12px; " + "padding-left: 13px;" bad_rule = "padding-bottom: null;" expect(".padding-false-third").to have_ruleset(ruleset) expect(".padding-false-third").to_not have_rule(bad_rule) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/text_inputs_spec.rb
spec/bourbon/library/text_inputs_spec.rb
require "spec_helper" describe "text-inputs" do before(:all) do ParserSupport.parse_file("library/text-inputs") @inputs_list = %w( [type='color'] [type='date'] [type='datetime'] [type='datetime-local'] [type='email'] [type='month'] [type='number'] [type='password'] [type='search'] [type='tel'] [type='text'] [type='time'] [type='url'] [type='week'] input:not([type]) textarea ) end context "expands plain text inputs" do it "finds selectors" do list = @inputs_list.join(", ") ruleset = "content: #{list};" expect(".all-text-inputs").to have_ruleset(ruleset) end end context "expands active text inputs" do it "finds selectors" do list = @inputs_list.map { |input| "#{input}:active" } list = list.join(", ") ruleset = "content: #{list};" expect(".all-text-inputs-active").to have_ruleset(ruleset) end end context "expands focus text inputs" do it "finds selectors" do list = @inputs_list.map { |input| "#{input}:focus" } list = list.join(", ") ruleset = "content: #{list};" expect(".all-text-inputs-focus").to have_ruleset(ruleset) end end context "expands hover text inputs" do it "finds selectors" do list = @inputs_list.map { |input| "#{input}:hover" } list = list.join(", ") ruleset = "content: #{list};" expect(".all-text-inputs-hover").to have_ruleset(ruleset) end end context "expands invalid text inputs" do it "finds selectors" do list = @inputs_list.map { |input| "#{input}:invalid" } list = list.join(", ") ruleset = "content: #{list};" expect(".all-text-inputs-invalid").to have_ruleset(ruleset) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/margin_spec.rb
spec/bourbon/library/margin_spec.rb
require "spec_helper" describe "margin" do before(:all) do ParserSupport.parse_file("library/margin") end context "called with one size" do it "applies same width to all sides" do rule = "margin: 1px" expect(".margin-all").to have_rule(rule) end end context "called with two sizes" do it "applies to alternating sides" do rule = "margin: 2px 3px" expect(".margin-alternate").to have_rule(rule) end end context "called with three sizes" do it "applies second width to left and right" do rule = "margin: 4px 5px 6px" expect(".margin-implied-left").to have_rule(rule) end end context "called with four sizes" do it "applies different widths to all sides" do rule = "margin: 7px 8px 9px 10px" expect(".margin-explicit").to have_rule(rule) end end context "called with null values" do it "writes rules for other three" do ruleset = "margin-top: 11px; " + "margin-right: 12px; " + "margin-left: 13px;" bad_rule = "margin-bottom: null;" expect(".margin-false-third").to have_ruleset(ruleset) expect(".margin-false-third").to_not have_rule(bad_rule) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/tint_spec.rb
spec/bourbon/library/tint_spec.rb
require "spec_helper" describe "tint" do before(:all) do ParserSupport.parse_file("library/tint") end context "called on white" do it "still returns white" do expect(".tint-white").to have_rule("color: white") end end context "called on black" do it "tints black" do expect(".tint-black").to have_rule("color: gray") end end context "called on red" do it "tints red" do expect(".tint-red").to have_rule("color: #ff4040") end end context "called on gray" do it "tints gray" do expect(".tint-gray").to have_rule("color: #c6c6c6") end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/font_face_spec_2.rb
spec/bourbon/library/font_face_spec_2.rb
require "spec_helper" describe "font-face" do before(:all) do ParserSupport.parse_file("library/font-face-5") end context "called with additional CSS rules" do it "outputs defaults with additional content" do ruleset = 'font-family: "calibre"; ' + 'src: url("fonts/calibre.woff2") format("woff2"), ' + 'url("fonts/calibre.woff") format("woff"); ' + "font-style: normal;" + "font-weight: 600;" + "unicode-range: U+26;" expect("@font-face").to have_ruleset(ruleset) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/ellipsis_spec.rb
spec/bourbon/library/ellipsis_spec.rb
require "spec_helper" describe "ellipsis" do before(:all) do ParserSupport.parse_file("library/ellipsis") end context "called on element" do it "adds ellipsis" do ruleset = "display: inline-block; " + "max-width: 100%; " + "overflow: hidden; " + "text-overflow: ellipsis; " + "white-space: nowrap; " + "word-wrap: normal;" expect(".ellipsis").to have_ruleset(ruleset) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/size_spec.rb
spec/bourbon/library/size_spec.rb
require "spec_helper" describe "size" do before(:all) do ParserSupport.parse_file("library/size") end context "called with one size" do it "applies same width to both height and width" do rule = "height: 10px; width: 10px;" expect(".size-implicit").to have_ruleset(rule) end end context "called with two sizes" do it "applies to height and width" do rule = "height: 2em; width: 1em;" expect(".size-both").to have_ruleset(rule) end end context "called with auto" do it "applies to auto to height" do rule = "height: auto; width: 100px;" expect(".size-auto").to have_ruleset(rule) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/clearfix_spec.rb
spec/bourbon/library/clearfix_spec.rb
require "spec_helper" describe "clearfix" do before(:all) do ParserSupport.parse_file("library/clearfix") end context "called on element" do it "adds clearfix" do input = ".clearfix::after" ruleset = "clear: both; " + 'content: ""; ' + "display: block;" expect(input).to have_ruleset(ruleset) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/hide_text_spec.rb
spec/bourbon/library/hide_text_spec.rb
require "spec_helper" describe "hide-text" do before(:all) do ParserSupport.parse_file("library/hide-text") end context "called on element" do it "adds hide-text" do ruleset = "overflow: hidden; " + "text-indent: 101%; " + "white-space: nowrap;" expect(".hide-text").to have_ruleset(ruleset) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/prefixer_spec.rb
spec/bourbon/library/prefixer_spec.rb
require "spec_helper" describe "prefixer" do before(:all) do ParserSupport.parse_file("library/prefixer") end context "called with no prefixes" do it "outputs the spec" do rule = "appearance: none;" expect(".prefix").to have_ruleset(rule) end end context "called with one prefix" do it "applies the prefix to the property" do rule = "-webkit-appearance: none; " + "appearance: none;" expect(".prefix--webkit").to have_ruleset(rule) end end context "called with multiple prefixes" do it "applies the prefixes to the property" do rule = "-moz-appearance: none; " + "-ms-appearance: none; " + "appearance: none;" expect(".prefix--moz-ms").to have_ruleset(rule) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/shade_spec.rb
spec/bourbon/library/shade_spec.rb
require "spec_helper" describe "shade" do before(:all) do ParserSupport.parse_file("library/shade") end context "called on white" do it "shades white" do expect(".shade-white").to have_rule("color: #404040") end end context "called on black" do it "still returns black" do expect(".shade-black").to have_rule("color: black") end end context "called on red" do it "shades red" do expect(".shade-red").to have_rule("color: #bf0000") end end context "called on gray" do it "shades gray" do expect(".shade-gray").to have_rule("color: #171717") end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/font_face_spec_3.rb
spec/bourbon/library/font_face_spec_3.rb
require "spec_helper" describe "font-face" do before(:all) do ParserSupport.parse_file("library/font-face-3") end context "called with defaults" do it "outputs defaults" do ruleset = 'font-family: "pitch";' + 'src: font-url("/fonts/pitch.woff2") format("woff2");' expect("@font-face").to have_ruleset(ruleset) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/position_spec.rb
spec/bourbon/library/position_spec.rb
require "spec_helper" describe "position" do before(:all) do ParserSupport.parse_file("library/position") end context "called with one size" do it "applies same width to all sides" do ruleset = "position: fixed; " + "top: 1em; " + "right: 1em; " + "bottom: 1em; " + "left: 1em;" expect(".position-all").to have_ruleset(ruleset) end end context "called with two sizes" do it "applies to alternating sides" do ruleset = "position: absolute; " + "top: 2px; " + "right: 3px; " + "bottom: 2px; " + "left: 3px;" expect(".position-alternate").to have_ruleset(ruleset) end end context "called with three sizes" do it "applies second width to left and right" do ruleset = "position: relative; " + "top: 4px; " + "right: 5px; " + "bottom: 6px; " + "left: 5px;" expect(".position-implied-left").to have_ruleset(ruleset) end end context "called with four sizes" do it "applies different widths to all sides" do ruleset = "position: fixed; " + "top: 7px; " + "right: 8px; " + "bottom: 9px; " + "left: 10px;" expect(".position-explicit").to have_ruleset(ruleset) end end context "called with null values" do it "writes rules for others" do ruleset = "position: static; " + "top: 11px; " + "left: 13px;" bad_rule = "position-bottom: null; position-right: null;" expect(".position-false-third").to have_ruleset(ruleset) expect(".position-false-third").to_not have_rule(bad_rule) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/hide_visually_spec.rb
spec/bourbon/library/hide_visually_spec.rb
require "spec_helper" describe "hide-visually" do before(:all) do ParserSupport.parse_file("library/hide-visually") end context "called on element" do it "adds properties to hide the element" do ruleset = "border: 0; " + "clip: rect(1px, 1px, 1px, 1px); " + "clip-path: inset(100%); " + "height: 1px; " + "overflow: hidden; " + "padding: 0; " + "position: absolute; " + "white-space: nowrap; " + "width: 1px;" expect(".hide-visually").to have_ruleset(ruleset) end end context "called with unhide argument" do it "adds properties to reverse the hiding of the element" do ruleset = "clip: auto; " + "clip-path: none; " + "height: auto; " + "overflow: visible; " + "position: static; " + "white-space: inherit; " + "width: auto;" expect(".hide-visually--unhide").to have_ruleset(ruleset) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/contrast_switch_spec.rb
spec/bourbon/library/contrast_switch_spec.rb
require "spec_helper" describe "contrast-switch" do before(:all) do ParserSupport.parse_file("library/contrast-switch") end context "called with a light base color" do it "outputs the dark color" do rule = "color: #000;" expect(".contrast-switch-light-base").to have_ruleset(rule) end end context "called with a dark base color" do it "outputs the light color" do rule = "color: #eee;" expect(".contrast-switch-dark-base").to have_ruleset(rule) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/border_radius_spec.rb
spec/bourbon/library/border_radius_spec.rb
require "spec_helper" describe "border-radius" do before(:all) do ParserSupport.parse_file("library/border-radius") end context "called with one argument" do it "applies to correct sides" do top = "border-top-left-radius: 1em; " + "border-top-right-radius: 1em;" left = "border-bottom-left-radius: 2em; " + "border-top-left-radius: 2em;" right = "border-bottom-right-radius: 3em; " + "border-top-right-radius: 3em;" bottom = "border-bottom-left-radius: 4em; " + "border-bottom-right-radius: 4em;" expect(".border-top-radius").to have_ruleset(top) expect(".border-left-radius").to have_ruleset(left) expect(".border-right-radius").to have_ruleset(right) expect(".border-bottom-radius").to have_ruleset(bottom) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/border_color_spec.rb
spec/bourbon/library/border_color_spec.rb
require "spec_helper" describe "border-color" do before(:all) do ParserSupport.parse_file("library/border-color") end context "called with one color" do it "applies same color to all sides" do rule = "border-color: #f00" expect(".border-color-all").to have_rule(rule) end end context "called with two colors" do it "applies to alternating sides" do rule = "border-color: #0f0 #00f" expect(".border-color-alternate").to have_rule(rule) end end context "called with three colors" do it "applies second color to left and right" do rule = "border-color: #f00 #0f0 #00f" expect(".border-color-implied-left").to have_rule(rule) end end context "called with four colors" do it "applies different colors to all sides" do rule = "border-color: #00f #0f0 #f00 #ff0" expect(".border-color-explicit").to have_rule(rule) end end context "called with null values" do it "writes rules for other three" do ruleset = "border-top-color: #0f0; " + "border-right-color: #ff0; " + "border-left-color: #00f;" bad_rule = "border-bottom-color: null;" expect(".border-color-false-third").to have_ruleset(ruleset) expect(".border-color-false-third").to_not have_rule(bad_rule) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/buttons_spec.rb
spec/bourbon/library/buttons_spec.rb
require "spec_helper" describe "buttons" do before(:all) do ParserSupport.parse_file("library/buttons") @buttons_list = %w( button [type='button'] [type='reset'] [type='submit'] ) end context "expands plain buttons" do it "finds selectors" do list = @buttons_list.join(", ") ruleset = "content: #{list};" expect(".all-buttons").to have_ruleset(ruleset) end end context "expands active buttons" do it "finds selectors" do list = @buttons_list.map { |input| "#{input}:active" } list = list.join(", ") ruleset = "content: #{list};" expect(".all-buttons-active").to have_ruleset(ruleset) end end context "expands focus buttons" do it "finds selectors" do list = @buttons_list.map { |input| "#{input}:focus" } list = list.join(", ") ruleset = "content: #{list};" expect(".all-buttons-focus").to have_ruleset(ruleset) end end context "expands hover buttons" do it "finds selectors" do list = @buttons_list.map { |input| "#{input}:hover" } list = list.join(", ") ruleset = "content: #{list};" expect(".all-buttons-hover").to have_ruleset(ruleset) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/font_stacks_spec.rb
spec/bourbon/library/font_stacks_spec.rb
require "spec_helper" describe "font-stacks" do before(:all) do ParserSupport.parse_file("library/font-stacks") end context "stacks used in variable" do it "output stacks" do helvetica = '"Helvetica Neue", "Helvetica", "Arial", sans-serif' lucida_grande = '"Lucida Grande", "Lucida Sans Unicode", ' + '"Geneva", "Verdana", sans-serif' verdana = '"Verdana", "Geneva", sans-serif' garamond = '"Garamond", "Baskerville", "Baskerville Old Face", ' + '"Hoefler Text", "Times New Roman", serif' georgia = '"Georgia", "Times", "Times New Roman", serif' hoefler_text = '"Hoefler Text", "Baskerville Old Face", ' + '"Garamond", "Times New Roman", serif' consolas = '"Consolas", "monaco", monospace' courier_new = '"Courier New", "Courier", "Lucida Sans Typewriter", ' + '"Lucida Typewriter", monospace' monaco = '"Monaco", "Consolas", "Lucida Console", monospace' system = 'system-ui, -apple-system, BlinkMacSystemFont, "Avenir Next", ' + '"Avenir", "Segoe UI", "Lucida Grande", "Helvetica Neue", ' + '"Helvetica", "Fira Sans", "Roboto", "Noto", "Droid Sans", ' + '"Cantarell", "Oxygen", "Ubuntu", "Franklin Gothic Medium", ' + '"Century Gothic", "Liberation Sans", sans-serif' expect(".helvetica").to have_value(helvetica) expect(".lucida-grande").to have_value(lucida_grande) expect(".verdana").to have_value(verdana) expect(".garamond").to have_value(garamond) expect(".georgia").to have_value(georgia) expect(".hoefler-text").to have_value(hoefler_text) expect(".consolas").to have_value(consolas) expect(".courier-new").to have_value(courier_new) expect(".monaco").to have_value(monaco) expect(".system").to have_value(system) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/overflow_wrap_spec.rb
spec/bourbon/library/overflow_wrap_spec.rb
require "spec_helper" describe "overflow-wrap" do before(:all) do ParserSupport.parse_file("library/overflow-wrap") end context "called on element" do it "adds overflow-wrap and word-wrap" do input = ".overflow-wrap" ruleset = "word-wrap: break-word; " + "overflow-wrap: break-word;" expect(input).to have_ruleset(ruleset) end end context "called on element with normal" do it "sets values as normal" do input = ".overflow-wrap-normal" ruleset = "word-wrap: normal; " + "overflow-wrap: normal;" expect(input).to have_ruleset(ruleset) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/triangle_spec.rb
spec/bourbon/library/triangle_spec.rb
require "spec_helper" describe "triangle" do before(:all) do ParserSupport.parse_file("library/triangle") end context "called with defaults" do it "outputs the properties" do ruleset = "border-style: solid; " + "height: 0; " + "width: 0; " + "border-color: transparent transparent #b25c9c; " + "border-width: 0 1rem 1rem;" expect(".triangle--up").to have_ruleset(ruleset) end end context "called with arguments" do it "outputs the properties" do ruleset = "border-style: solid; " + "height: 0; " + "width: 0; " + "border-color: transparent transparent transparent #aaa; " + "border-width: 6px 0 6px 5px;" expect(".triangle--right").to have_ruleset(ruleset) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/border_width_spec.rb
spec/bourbon/library/border_width_spec.rb
require "spec_helper" describe "border-width" do before(:all) do ParserSupport.parse_file("library/border-width") end context "called with one color" do it "applies same width to all sides" do rule = "border-width: 1px" expect(".border-width-all").to have_rule(rule) end end context "called with two widths" do it "applies to alternating sides" do rule = "border-width: 2px 3px" expect(".border-width-alternate").to have_rule(rule) end end context "called with three widths" do it "applies second width to left and right" do rule = "border-width: 4px 5px 6px" expect(".border-width-implied-left").to have_rule(rule) end end context "called with four widths" do it "applies different widths to all sides" do rule = "border-width: 7px 8px 9px 10px" expect(".border-width-explicit").to have_rule(rule) end end context "called with null values" do it "writes rules for other three" do ruleset = "border-top-width: 11px; " + "border-right-width: 12px; " + "border-left-width: 13px;" bad_rule = "border-bottom-width: null;" expect(".border-width-false-third").to have_ruleset(ruleset) expect(".border-width-false-third").to_not have_rule(bad_rule) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/border_style_spec.rb
spec/bourbon/library/border_style_spec.rb
require "spec_helper" describe "border-style" do before(:all) do ParserSupport.parse_file("library/border-style") end context "called with one style" do it "applies same style to all sides" do rule = "border-style: solid" expect(".border-style-all").to have_rule(rule) end end context "called with two styles" do it "applies to alternating sides" do rule = "border-style: dotted dashed" expect(".border-style-alternate").to have_rule(rule) end end context "called with three styles" do it "applies second style to left and right" do rule = "border-style: dashed double solid" expect(".border-style-implied-left").to have_rule(rule) end end context "called with four styles" do it "applies different styles to all sides" do rule = "border-style: dotted groove ridge none" expect(".border-style-explicit").to have_rule(rule) end end context "called with null values" do it "writes rules for other three" do ruleset = "border-top-style: inset; " + "border-right-style: none; " + "border-left-style: double;" bad_rule = "border-bottom-style: null;" expect(".border-style-false-third").to have_ruleset(ruleset) expect(".border-style-false-third").to_not have_rule(bad_rule) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/strip_unit_spec.rb
spec/bourbon/library/strip_unit_spec.rb
require "spec_helper" describe "strip-unit" do before(:all) do ParserSupport.parse_file("library/strip-unit") end context "called with px" do it "strips units" do expect(".px").to have_rule("width: 10") end end context "called with em" do it "strips units" do expect(".em").to have_rule("width: 2") end end context "called with rem" do it "strips units" do expect(".rem").to have_rule("width: 1.5") end end context "called with percent" do it "strips units" do expect(".percent").to have_rule("width: 20") end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/font_face_spec_1.rb
spec/bourbon/library/font_face_spec_1.rb
require "spec_helper" describe "font-face" do before(:all) do ParserSupport.parse_file("library/font-face-1") end context "called with defaults" do it "outputs defaults" do ruleset = 'font-family: "source-sans-pro"; ' + 'src: url("/fonts/source-sans-pro/source-sans-pro-regular.woff2") format("woff2"), url("/fonts/source-sans-pro/source-sans-pro-regular.woff") format("woff");' expect("@font-face").to have_ruleset(ruleset) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/library/modular_scale_spec.rb
spec/bourbon/library/modular_scale_spec.rb
require "spec_helper" describe "modular-scale" do before(:all) do ParserSupport.parse_file("library/modular-scale") end context "called with arguments (1, $value: 2em)" do it "outputs double the first value from the default scale" do expect(".one-base-two").to have_rule("font-size: 2.5em") end end context "called with arguments (1, $value: 3em)" do it "outputs triple the first value from the default scale" do expect(".one-base-three").to have_rule("font-size: 3.75em") end end context "called with arguments (1, $value: 4em 6em)" do it "outputs quadruple the first value from the default scale" do expect(".one-double-value").to have_rule("font-size: 1.024em") end end context "called with arguments (1, $ratio: $golden-ratio)" do it "output the first value from the golden ratio scale" do expect(".one-golden-ratio").to have_rule("font-size: 1.618em") end end context "called with argument (2)" do it "outputs the second value from the default scale" do expect(".two-base-one").to have_rule("font-size: 1.5625em") end end context "called with arguments (2, $value: 4em 6em)" do it "outputs sextuple the second value from the default scale" do expect(".two-double-value").to have_rule("font-size: 3.125em") end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/utilities/compact_shorthand_spec.rb
spec/bourbon/utilities/compact_shorthand_spec.rb
require "spec_helper" describe "compact-shorthand" do before(:all) do ParserSupport.parse_file("utilities/compact-shorthand") end context "compact-shorthand" do it "returns four values unaltered" do expect(".four-values-a").to have_rule("padding: 10px 20px 30px 40px") end it "returns four values when the left and right values are not equal" do expect(".four-values-b").to have_rule("padding: 5px 10px 5px 20px") end it "compacts four values to two values when the top/bottom and " + "left/right values are equal" do expect(".two-values").to have_rule("padding: 50px 100px") end it "compacts four values to one value when they all match" do expect(".one-value").to have_rule("padding: 10px") end it "skips null values" do expect(".null-value").to have_rule("padding: 10px 20px") end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/utilities/font_source_declaration_spec.rb
spec/bourbon/utilities/font_source_declaration_spec.rb
require "spec_helper" describe "font-source-declaration" do before(:all) do ParserSupport.parse_file("utilities/font-source-declaration") end context "called with pipeline" do it "returns pipeline path" do rule = 'src: font-url("b.woff2") format("woff2"), ' + 'font-url("b.woff") format("woff")' expect(".has-pipeline").to have_rule(rule) end end context "called with no pipeline" do it "does not return pipeline path" do rule = 'src: url("b.woff2") format("woff2"), ' + 'url("b.woff") format("woff")' expect(".no-pipeline").to have_rule(rule) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/utilities/fetch_bourbon_setting_spec.rb
spec/bourbon/utilities/fetch_bourbon_setting_spec.rb
require "spec_helper" describe "fetch-bourbon-setting" do before(:all) do ParserSupport.parse_file("utilities/fetch-bourbon-setting") end context "fetches the modular-scale-base setting" do it "and returns the default value" do expect(".test-1").to have_rule("content: 1em") end end context "fetches the rails-asset-pipeline setting" do it "and returns the user-overridden value" do expect(".test-2").to have_rule("content: true") end end context "called from the font-face mixin" do it "outputs user-overridden font file formats" do ruleset = 'font-family: "source-sans-pro"; ' + 'src: font-url("source-sans-pro-regular.woff2") ' + 'format("woff2"), ' + 'font-url("source-sans-pro-regular.woff") ' + 'format("woff");' expect("@font-face").to have_ruleset(ruleset) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/utilities/unpack_spec.rb
spec/bourbon/utilities/unpack_spec.rb
require "spec_helper" describe "unpack" do before(:all) do ParserSupport.parse_file("utilities/unpack") end context "single" do it "unpacks four identical measurements" do expect(".single").to have_rule("padding: 10px 10px 10px 10px") end end context "double" do it "unpacks identical measurements for top and bottom, and different identical measurements for left and right" do expect(".double").to have_rule("padding: 1em 2em 1em 2em") end end context "triple" do it "unpacks identical measurements for left and right" do expect(".triple").to have_rule("padding: 10px 20px 0 20px") end end context "quadruple" do it "unpacks four distict measurements" do expect(".quadruple").to have_rule("padding: 0 calc(1em + 10px) 20px 50px") end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/utilities/lightness_spec.rb
spec/bourbon/utilities/lightness_spec.rb
require "spec_helper" describe "lightness" do before(:all) do ParserSupport.parse_file("utilities/lightness") end context "called on black" do it "outputs a number between 0 and 1 to indicate lightness" do rule = "content: 0;" expect(".lightness-black").to have_ruleset(rule) end end context "called on white" do it "outputs a number between 0 and 1 to indicate lightness" do rule = "content: 1;" expect(".lightness-white").to have_ruleset(rule) end end context "called on gray" do it "outputs a number between 0 and 1 to indicate lightness" do rule = "content: 0.20503;" expect(".lightness-gray").to have_ruleset(rule) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/utilities/gamma_spec.rb
spec/bourbon/utilities/gamma_spec.rb
require "spec_helper" describe "gamma" do before(:all) do ParserSupport.parse_file("utilities/gamma") end context "called on a color channel" do it "outputs a gamma value between 0 and 1" do rule = "content: 0.12168;" expect(".gamma").to have_ruleset(rule) end end context "called on a full color channel" do it "outputs a gamma value between 0 and 1" do rule = "content: 1;" expect(".gamma-full").to have_ruleset(rule) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/utilities/assign_inputs_spec.rb
spec/bourbon/utilities/assign_inputs_spec.rb
require "spec_helper" describe "assign-inputs" do before(:all) do ParserSupport.parse_file("utilities/assign-inputs") @text_inputs_list = [ "[type='password']", "[type='text']", "textarea" ] end context "expands plain text inputs" do it "finds selectors" do @text_inputs_list.each do |input| expect(input).to have_rule("color: #f00") end end end context "expands text inputs with pseudo classes" do it "finds selectors" do list = @text_inputs_list.dup list.map! { |input| input + ":active" } list.each do |input| expect(input).to have_rule("color: #0f0") end end end context "expands text inputs when first in list" do it "finds selectors" do list = @text_inputs_list.dup list.push "select" list.each do |input| expect(input).to have_rule("color: #00f") end end end context "expands text inputs when middle of list" do it "finds selectors" do list = @text_inputs_list.dup list.unshift "[type=\"file\"]" list.each do |input| expect(input).to have_rule("color: #f0f") end end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/utilities/contrast_ratio_spec.rb
spec/bourbon/utilities/contrast_ratio_spec.rb
require "spec_helper" describe "contrast-ratio" do before(:all) do ParserSupport.parse_file("utilities/contrast-ratio") end context "calculates between white and black" do it "outputs the contrast ratio" do rule = "content: 21;" expect(".contrast-ratio-black").to have_ruleset(rule) end end context "calculates between white and blue" do it "outputs the contrast ratio" do rule = "content: 8.59247;" expect(".contrast-ratio-blue").to have_ruleset(rule) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/spec/bourbon/utilities/directional_property_spec.rb
spec/bourbon/utilities/directional_property_spec.rb
require "spec_helper" describe "directional-property" do before(:all) do ParserSupport.parse_file("utilities/directional-property") end context "directional-property" do it "returns property and values with four distinct lengths" do expect(".border-all").to have_rule("border-width: 2px 5px 8px 12px") end it "returns property and value with one length" do expect(".border-top").to have_rule("border-top: 10px") end it "returns property and value with vertical and horizontal values" do expect(".border-color").to have_rule("border-color: #fff #000") end it "returns properties for top and bottom margin" do ruleset = "margin-top: 20px; " + "margin-bottom: 10px;" expect(".margin-null").to have_ruleset(ruleset) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/lib/bourbon.rb
lib/bourbon.rb
require "bourbon/generator" module Bourbon if defined?(Rails) && defined?(Rails::Engine) class Engine < ::Rails::Engine initializer "bourbon.paths", group: :all do |app| app.config.assets.paths << File.expand_path("../core", __dir__) end end else begin require "sass" Sass.load_paths << File.expand_path("../core", __dir__) rescue LoadError end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/lib/bourbon/version.rb
lib/bourbon/version.rb
module Bourbon VERSION = "7.3.0".freeze end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/bourbon
https://github.com/thoughtbot/bourbon/blob/1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8/lib/bourbon/generator.rb
lib/bourbon/generator.rb
require "bourbon/version" require "fileutils" require "thor" require "pathname" module Bourbon class Generator < Thor map ["-v", "--version"] => :version desc "install", "Install Bourbon into your project" method_options :path => :string, :force => :boolean def install if bourbon_files_already_exist? && !options[:force] puts "Bourbon files already installed, doing nothing." else install_files puts "Bourbon files installed to #{install_path}/" end end desc "update", "Update Bourbon" method_options :path => :string def update if bourbon_files_already_exist? remove_bourbon_directory install_files puts "Bourbon files updated." else puts "No existing bourbon installation. Doing nothing." end end desc "version", "Show Bourbon version" def version say "Bourbon #{Bourbon::VERSION}" end private def bourbon_files_already_exist? install_path.exist? end def install_path @install_path ||= if options[:path] Pathname.new(File.join(options[:path], "bourbon")) else Pathname.new("bourbon") end end def install_files make_install_directory copy_in_scss_files end def remove_bourbon_directory FileUtils.rm_rf(install_path) end def make_install_directory FileUtils.mkdir_p(install_path) end def copy_in_scss_files FileUtils.cp_r(all_stylesheets, install_path) end def all_stylesheets Dir["#{stylesheets_directory}/*"] end def stylesheets_directory File.join(top_level_directory, "core") end def top_level_directory File.dirname(File.dirname(File.dirname(__FILE__))) end end end
ruby
MIT
1cd55ce9c0f1785ddecc617b3ba6a40a0c61b7b8
2026-01-04T15:38:44.363157Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/.github/REPRODUCTION_SCRIPT.rb
.github/REPRODUCTION_SCRIPT.rb
require "bundler/inline" gemfile(true) do source "https://rubygems.org" git_source(:github) { |repo| "https://github.com/#{repo}.git" } 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 # TODO: Update the schema to include the specific tables or columns necessary # to reproduct the bug create_table :posts, force: true do |t| t.string :body end end # TODO: Add any application specific code necessary to reproduce the bug class Post < ActiveRecord::Base end FactoryBot.define do # TODO: Write the factory definitions necessary to reproduce the bug factory :post do body { "Post body" } end end class FactoryBotTest < Minitest::Test def test_factory_bot_stuff # TODO: Write a failing test case to demonstrate what isn't working as # expected body_override = "Body override" post = FactoryBot.build(:post, body: body_override) assert_equal post.body, body_override end end # Run the tests with `ruby <filename>`
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/features/support/env.rb
features/support/env.rb
PROJECT_ROOT = File.expand_path(File.join(File.dirname(__FILE__), "..", "..")) require "simplecov" if RUBY_ENGINE == "ruby" $: << File.join(PROJECT_ROOT, "lib") require "active_record" require "factory_bot" require "aruba/cucumber"
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/features/support/factories.rb
features/support/factories.rb
ActiveRecord::Base.establish_connection( adapter: "sqlite3", database: ":memory:" ) class CreateSchema < ActiveRecord::Migration[5.0] def self.up create_table :categories, force: true do |t| t.string :name end end end CreateSchema.suppress_messages { CreateSchema.migrate(:up) } class Category < ActiveRecord::Base; end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/features/step_definitions/factory_bot_steps.rb
features/step_definitions/factory_bot_steps.rb
module FactoryBotDefinitionsHelper def append_file_to_factory_bot_definitions_path(path_to_file) FactoryBot.definition_file_paths ||= [] FactoryBot.definition_file_paths << path_to_file end end World(FactoryBotDefinitionsHelper) When(/^"([^"]*)" is added to FactoryBot's file definitions path$/) do |file_name| new_factory_file = File.join(expand_path("."), file_name.gsub(".rb", "")) append_file_to_factory_bot_definitions_path(new_factory_file) step %(I find definitions) end When(/^"([^"]*)" is added to FactoryBot's file definitions path as an absolute path$/) do |file_name| new_factory_file = File.expand_path(File.join(expand_path("."), file_name.gsub(".rb", ""))) append_file_to_factory_bot_definitions_path(new_factory_file) step %(I find definitions) end When(/^I create a "([^"]*)" instance from FactoryBot$/) do |factory_name| FactoryBot.create(factory_name) end When(/^I find definitions$/) do FactoryBot.find_definitions end When(/^I reload factories$/) do FactoryBot.reload end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/features/step_definitions/database_steps.rb
features/step_definitions/database_steps.rb
Then(/^I should find the following for the last category:$/) do |table| table.hashes.first.each do |key, value| expect(Category.last.attributes[key].to_s).to eq value end end Before do Category.delete_all end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot_spec.rb
spec/factory_bot_spec.rb
describe FactoryBot do it "finds a registered strategy" do FactoryBot.register_strategy(:strategy_name, :strategy_class) expect(FactoryBot.strategy_by_name(:strategy_name)) .to eq :strategy_class end describe ".use_parent_strategy" do it "is true by default" do expect(FactoryBot.use_parent_strategy).to be true end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/spec_helper.rb
spec/spec_helper.rb
# Set timeout when setting sequences require "rspec" require "rspec/its" require "simplecov" if RUBY_ENGINE == "ruby" require "factory_bot" FactoryBot.sequence_setting_timeout = 0.5 if RUBY_ENGINE == "jruby" # Workaround for issue in I18n/JRuby combo. # See https://github.com/jruby/jruby/issues/6547 and # https://github.com/ruby-i18n/i18n/issues/555 require "i18n/backend" require "i18n/backend/simple" end Dir["spec/support/**/*.rb"].each { |f| require File.expand_path(f) } RSpec.configure do |config| config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on a # real object. This is generally recommended, and will default to `true` in # RSpec 4. mocks.verify_partial_doubles = true end config.include DeclarationMatchers config.before do FactoryBot.reload end config.order = :random Kernel.srand config.seed config.example_status_persistence_file_path = "tmp/rspec_examples.txt" end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/support/macros/deprecation.rb
spec/support/macros/deprecation.rb
require "active_support" RSpec.configure do |config| config.around :example, silence_deprecation: true do |example| with_temporary_assignment(FactoryBot::Deprecation, :silenced, true) do example.run end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/support/macros/temporary_assignment.rb
spec/support/macros/temporary_assignment.rb
module TemporaryAssignment def with_temporary_assignment(assignee, attribute, temporary_value) original_value = assignee.public_send(attribute) attribute_setter = "#{attribute}=" assignee.public_send(attribute_setter, temporary_value) yield ensure assignee.public_send(attribute_setter, original_value) end end RSpec.configure do |config| config.include TemporaryAssignment end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/support/macros/define_constant.rb
spec/support/macros/define_constant.rb
require "active_record" module DefineConstantMacros def define_class(path, base = Object, &block) const = stub_const(path, Class.new(base)) const.class_eval(&block) if block const end def define_model(name, columns = {}, &block) model = define_class(name, ActiveRecord::Base, &block) create_table(model.table_name) do |table| columns.each do |column_name, type| table.column column_name, type end end model end def create_table(table_name, &block) connection = ActiveRecord::Base.connection begin connection.execute("DROP TABLE IF EXISTS #{table_name}") connection.create_table(table_name, &block) created_tables << table_name connection rescue Exception => e # rubocop:disable Lint/RescueException connection.execute("DROP TABLE IF EXISTS #{table_name}") raise e end end def clear_generated_tables created_tables.each do |table_name| clear_generated_table(table_name) end created_tables.clear end def clear_generated_table(table_name) ActiveRecord::Base .connection .execute("DROP TABLE IF EXISTS #{table_name}") end private def created_tables @created_tables ||= [] end end RSpec.configure do |config| config.include DefineConstantMacros config.before(:all) do ActiveRecord::Base.establish_connection( adapter: "sqlite3", database: ":memory:" ) end config.after do clear_generated_tables end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/support/shared_examples/strategy.rb
spec/support/shared_examples/strategy.rb
shared_examples_for "strategy without association support" do let(:factory) { double("associate_factory") } let(:attribute) { FactoryBot::Attribute::Association.new(:user, :user, {}) } def association_named(name, overrides) runner = FactoryBot::FactoryRunner.new(name, :build, [overrides]) subject.association(runner) end before do allow(FactoryBot::Internal).to receive(:factory_by_name).and_return factory allow(factory).to receive(:compile) allow(factory).to receive(:run) end it "returns nil when accessing an association" do expect(association_named(:user, {})).to be_nil end end shared_examples_for "strategy with association support" do |factory_bot_strategy_name| let(:factory) { double("associate_factory") } def association_named(name, strategy, overrides) runner = FactoryBot::FactoryRunner.new(name, strategy, [overrides]) subject.association(runner) end before do allow(FactoryBot::Internal).to receive(:factory_by_name).and_return factory allow(factory).to receive(:compile) allow(factory).to receive(:run) end it "runs the factory with the correct overrides" do association_named(:author, factory_bot_strategy_name, great: "value") expect(factory).to have_received(:run).with(factory_bot_strategy_name, great: "value") end it "finds the factory with the correct factory name" do association_named(:author, factory_bot_strategy_name, great: "value") expect(FactoryBot::Internal).to have_received(:factory_by_name).with(:author) end end shared_examples_for "strategy with strategy: :build" do |factory_bot_strategy_name| let(:factory) { double("associate_factory") } def association_named(name, overrides) runner = FactoryBot::FactoryRunner.new(name, overrides[:strategy], [overrides.except(:strategy)]) subject.association(runner) end before do allow(FactoryBot::Internal).to receive(:factory_by_name).and_return factory allow(factory).to receive(:compile) allow(factory).to receive(:run) end it "runs the factory with the correct overrides" do association_named(:author, strategy: :build, great: "value") expect(factory).to have_received(:run).with(factory_bot_strategy_name, great: "value") end it "finds the factory with the correct factory name" do association_named(:author, strategy: :build, great: "value") expect(FactoryBot::Internal).to have_received(:factory_by_name).with(:author) end end shared_examples_for "strategy with callbacks" do |*callback_names| let(:result_instance) do define_class("ResultInstance") { attr_accessor :id }.new end let(:evaluation) do double("evaluation", object: result_instance, notify: true, create: nil) end it "runs the callbacks #{callback_names} with the evaluation's object" do subject.result(evaluation) callback_names.each do |name| expect(evaluation).to have_received(:notify).with(name, evaluation.object) end end it "returns the object from the evaluation" do expect(subject.result(evaluation)).to eq evaluation.object end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/support/matchers/callback.rb
spec/support/matchers/callback.rb
RSpec::Matchers.define :have_callback do |callback_name| match do |instance| instance.callbacks.include?(FactoryBot::Callback.new(callback_name, @block)) end chain :with_block do |block| @block = block end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/support/matchers/be_about_now.rb
spec/support/matchers/be_about_now.rb
RSpec::Matchers.define :be_about_now do match do |actual| expect(actual).to be_within(2.seconds).of(Time.now) end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/support/matchers/declaration.rb
spec/support/matchers/declaration.rb
module DeclarationMatchers def have_dynamic_declaration(name) DeclarationMatcher.new(:dynamic).named(name) end def have_association_declaration(name) DeclarationMatcher.new(:association).named(name) end def have_implicit_declaration(name) DeclarationMatcher.new(:implicit).named(name) end class DeclarationMatcher def initialize(declaration_type) @declaration_type = declaration_type end def matches?(subject) subject.declarations.include?(expected_declaration) end def named(name) @name = name self end def ignored @ignored = true self end def with_value(value) @value = value self end def with_factory(factory) @factory = factory self end def with_options(options) @options = options self end def failure_message [ "expected declarations to include declaration of type #{@declaration_type}", @options ? "with options #{options}" : nil ].compact.join " " end private def expected_declaration case @declaration_type when :dynamic then FactoryBot::Declaration::Dynamic.new(@name, ignored?, @value) when :implicit then FactoryBot::Declaration::Implicit.new(@name, @factory, ignored?) when :association if @options FactoryBot::Declaration::Association.new(@name, options) else FactoryBot::Declaration::Association.new(@name) end end end def ignored? !!@ignored end def options @options || {} end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/support/matchers/raise_did_you_mean_error.rb
spec/support/matchers/raise_did_you_mean_error.rb
RSpec::Matchers.define :raise_did_you_mean_error do supports_block_expectations match do |actual| # detailed_message introduced in Ruby 3.2 for cleaner integration with # did_you_mean. See https://bugs.ruby-lang.org/issues/18564 matcher = if KeyError.method_defined?(:detailed_message) raise_error( an_instance_of(KeyError) .and(having_attributes(detailed_message: /Did you mean\?/)) ) else raise_error(KeyError, /Did you mean\?/) end expect(&actual).to matcher end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/support/matchers/trait.rb
spec/support/matchers/trait.rb
RSpec::Matchers.define :have_trait do |trait_name| match do |instance| instance.defined_traits.any? do |trait| trait.name == trait_name.to_s && trait.send(:block) == @block end end chain :with_block do |block| @block = block end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/support/matchers/delegate.rb
spec/support/matchers/delegate.rb
RSpec::Matchers.define :delegate do |delegated_method| chain :to do |target_method| @target_method = target_method end chain :as do |method_on_target| @method_on_target = method_on_target end chain :with_arguments do |args| @args = args end match do |instance| @instance = instance @args ||= [] return_value = "stubbed return value" method_on_target = @method_on_target || delegated_method stubbed_target = double("stubbed_target", method_on_target => return_value) allow(@instance).to receive(@target_method).and_return stubbed_target begin @instance.send(delegated_method, *@args) == return_value rescue NoMethodError false end end failure_message do if Class === @instance message = "expected #{@instance.name} " prefix = "." else message = "expected #{@instance.class.name} " prefix = "#" end message << "to delegate #{prefix}#{delegated_method} to #{prefix}#{@target_method}" if @method_on_target message << ".#{@method_on_target}" end message end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/support/containers/test_log.rb
spec/support/containers/test_log.rb
require "forwardable" ## # Designed for tests to log output for later evaluation # module TestLog class << self extend Forwardable def_delegators :log_array, :<<, :[], :size, :first, :last def_delegators :log_array, :map, :in?, :include?, :inspect def all Thread.current[:my_thread_safe_test_log] ||= [] end def reset! Thread.current[:my_thread_safe_test_log] = [] end private def log_array Thread.current[:my_thread_safe_test_log] ||= [] end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/callbacks_spec.rb
spec/acceptance/callbacks_spec.rb
describe "callbacks" do before do define_model("User", first_name: :string, last_name: :string) end context "with strategy callbacks" do before do FactoryBot.define do factory :user_with_callbacks, class: :user do after(:stub) { |user| user.first_name = "Stubby" } after(:build) { |user| user.first_name = "Buildy" } after(:create) { |user| user.last_name = "Createy" } end factory :user_with_inherited_callbacks, parent: :user_with_callbacks do after(:stub) { |user| user.last_name = "Double-Stubby" } after(:build) { |user| user.first_name = "Child-Buildy" } end factory :user_with_multi_called_callbacks, class: :user do first_name { "Jane" } trait(:alias_2) { alias_1 } trait(:alias_1) { surname } trait :surname do after(:build) { |user| user.first_name += " Doe" } end end end end it "runs the after(:stub) callback when stubbing" do user = FactoryBot.build_stubbed(:user_with_callbacks) expect(user.first_name).to eq "Stubby" end it "runs the after(:build) callback when building" do user = FactoryBot.build(:user_with_callbacks) expect(user.first_name).to eq "Buildy" end it "runs both the after(:build) and after(:create) callbacks when creating" do user = FactoryBot.create(:user_with_callbacks) expect(user.first_name).to eq "Buildy" expect(user.last_name).to eq "Createy" end it "runs both the after(:stub) callback on the factory and the inherited after(:stub) callback" do user = FactoryBot.build_stubbed(:user_with_inherited_callbacks) expect(user.first_name).to eq "Stubby" expect(user.last_name).to eq "Double-Stubby" end it "runs child callback after parent callback" do user = FactoryBot.build(:user_with_inherited_callbacks) expect(user.first_name).to eq "Child-Buildy" end it "only runs each callback once per instance" do user_1 = FactoryBot.build(:user_with_multi_called_callbacks, :surname, :alias_1, :alias_2) user_2 = FactoryBot.build(:user_with_multi_called_callbacks, :alias_1, :alias_2, :surname) user_3 = FactoryBot.build(:user_with_multi_called_callbacks, :alias_2, :surname, :alias_1) expect(user_1.first_name).to eq "Jane Doe" expect(user_2.first_name).to eq "Jane Doe" expect(user_3.first_name).to eq "Jane Doe" end end # with strategy callbacks context "with before(:all) and after(:all) included" do context "are executed in the correct order" do before do FactoryBot.define do before(:all) { TestLog << "global before-all called" } after(:all) { TestLog << "global after-all called" } before(:build) { TestLog << "global before-build called" } after(:build) { TestLog << "global after-build called" } before(:create) { TestLog << "global before-create called" } after(:create) { TestLog << "global after-create called" } factory :parent, class: :user do before(:all) { TestLog << "parent before-all called" } after(:all) { TestLog << "parent after-all called" } before(:build) { TestLog << "parent before-build called" } after(:build) { TestLog << "parent after-build called" } before(:create) { TestLog << "parent before-create called" } after(:create) { TestLog << "parent after-create called" } trait :parent_trait_1 do before(:all) { TestLog << "parent-trait-1 before-all called" } after(:all) { TestLog << "parent-trait-1 after-all called" } before(:build) { TestLog << "parent-trait-1 before-build called" } after(:build) { TestLog << "parent-trait-1 after-build called" } before(:create) { TestLog << "parent-trait-1 before-create called" } after(:create) { TestLog << "parent-trait-1 after-create called" } end trait :parent_trait_2 do before(:all) { TestLog << "parent-trait-2 before-all called" } after(:all) { TestLog << "parent-trait-2 after-all called" } before(:build) { TestLog << "parent-trait-2 before-build called" } after(:build) { TestLog << "parent-trait-2 after-build called" } before(:create) { TestLog << "parent-trait-2 before-create called" } after(:create) { TestLog << "parent-trait-2 after-create called" } end end factory :child, parent: :parent do before(:all) { TestLog << "child before-all called" } after(:create) { TestLog << "child after-create called" } after(:build) { TestLog << "child after-build called" } before(:build) { TestLog << "child before-build called" } before(:create) { TestLog << "child before-create called" } after(:all) { TestLog << "child after-all called" } trait :child_trait do before(:all) { TestLog << "child-trait before-all called" } after(:all) { TestLog << "child-trait after-all called" } before(:build) { TestLog << "child-trait before-build called" } after(:build) { TestLog << "child-trait after-build called" } before(:create) { TestLog << "child-trait before-create called" } after(:create) { TestLog << "child-trait after-create called" } end end end end before(:each) { TestLog.reset! } it "with trait callbacks executed in the order requested" do # Note: trait callbacks are executed AFTER any factory callbacks and # in the order they are requested. # FactoryBot.create(:child, :parent_trait_2, :child_trait, :parent_trait_1) expect(TestLog.size).to eq 36 # before(:all) expect(TestLog[0..5]).to eq [ "global before-all called", "parent before-all called", "child before-all called", "parent-trait-2 before-all called", "child-trait before-all called", "parent-trait-1 before-all called" ] # before(:build) expect(TestLog[6..11]).to eq [ "global before-build called", "parent before-build called", "child before-build called", "parent-trait-2 before-build called", "child-trait before-build called", "parent-trait-1 before-build called" ] # after(:build) expect(TestLog[12..17]).to eq [ "global after-build called", "parent after-build called", "child after-build called", "parent-trait-2 after-build called", "child-trait after-build called", "parent-trait-1 after-build called" ] # before(:create) expect(TestLog[18..23]).to eq [ "global before-create called", "parent before-create called", "child before-create called", "parent-trait-2 before-create called", "child-trait before-create called", "parent-trait-1 before-create called" ] # after(:create) expect(TestLog[24..29]).to eq [ "global after-create called", "parent after-create called", "child after-create called", "parent-trait-2 after-create called", "child-trait after-create called", "parent-trait-1 after-create called" ] # after(:all) expect(TestLog[30..35]).to eq [ "global after-all called", "parent after-all called", "child after-all called", "parent-trait-2 after-all called", "child-trait after-all called", "parent-trait-1 after-all called" ] end end # ordered correctly context "with context provided to before(:all)" do before(:each) { TestLog.reset! } it "receives 'nil' as the instance" do FactoryBot.define do before(:all) { |user| TestLog << "Global instance: #{user}" } factory :user do before(:all) { |user| TestLog << "Factory instance: #{user}" } end end FactoryBot.build(:user) expect(TestLog.first).to eq "Global instance: " expect(TestLog.last).to eq "Factory instance: " end it "receives the context, without an instance" do FactoryBot.define do before(:all) do |user, context| TestLog << "Global strategy: #{context.instance_values["build_strategy"].to_sym}" TestLog << "Global instance: #{context.instance}" end factory :user do before(:all) do |user, context| TestLog << "Factory strategy: #{context.instance_values["build_strategy"].to_sym}" TestLog << "Factory instance: #{context.instance}" end end end FactoryBot.build(:user) expect(TestLog.all).to eq [ "Global strategy: build", "Global instance: ", "Factory strategy: build", "Factory instance: " ] end end # context: with context provided to before(:all) context "with context provided to after(:all)" do it "succeeds with the instance provided" do FactoryBot.define do after(:all) { |user| user.first_name = "Globy" } factory :user do after(:all) { |user| user.last_name = "Lasty" } end end user = FactoryBot.build(:user) expect(user.first_name).to eq "Globy" expect(user.last_name).to eq "Lasty" end it "succeeds with both the instance and context provided" do FactoryBot.define do after(:all) { |user, context| user.first_name = context.new_first_name } factory :user do transient do new_first_name { "New First Name" } new_last_name { "New Last Name" } end after(:all) { |user, context| user.last_name = context.new_last_name } end end user = FactoryBot.build(:user) expect(user.first_name).to eq "New First Name" expect(user.last_name).to eq "New Last Name" end end # context: with context provided to after(:all) end # context: with before(:all) and after(:all) callbacks included end # describe: callbacks describe "callbacks using Symbol#to_proc" do before do define_model("User") do def confirmed? !!@confirmed end def confirm! @confirmed = true end end FactoryBot.define do factory :user do after :build, &:confirm! end end end it "runs the callback correctly" do user = FactoryBot.build(:user) expect(user).to be_confirmed end end describe "callbacks using syntax methods without referencing FactoryBot explicitly" do before do define_model("User", first_number: :integer, last_number: :integer) FactoryBot.define do sequence(:sequence_1) sequence(:sequence_2) sequence(:sequence_3) factory :user do after(:stub) { generate(:sequence_3) } after(:build) { |user| user.first_number = generate(:sequence_1) } after(:create) { |user, _evaluator| user.last_number = generate(:sequence_2) } end end end it "works when the callback has no variables" do FactoryBot.build_stubbed(:user) expect(FactoryBot.generate(:sequence_3)).to eq 2 end it "works when the callback has one variable" do expect(FactoryBot.build(:user).first_number).to eq 1 end it "works when the callback has two variables" do expect(FactoryBot.create(:user).last_number).to eq 1 end end describe "custom callbacks" do let(:custom_before) do Class.new do def result(evaluation) evaluation.object.tap do |instance| evaluation.notify(:before_custom, instance) end end end end let(:custom_after) do Class.new do def result(evaluation) evaluation.object.tap do |instance| evaluation.notify(:after_custom, instance) end end end end let(:totally_custom) do Class.new do def result(evaluation) evaluation.object.tap do |instance| evaluation.notify(:totally_custom, instance) end end end end before do define_model("User", first_name: :string, last_name: :string) do def name [first_name, last_name].join(" ") end end FactoryBot.register_strategy(:custom_before, custom_before) FactoryBot.register_strategy(:custom_after, custom_after) FactoryBot.register_strategy(:totally_custom, totally_custom) FactoryBot.define do factory :user do first_name { "John" } last_name { "Doe" } before(:custom) { |instance| instance.first_name = "Overridden First" } after(:custom) { |instance| instance.last_name = "Overridden Last" } callback(:totally_custom) do |instance| instance.first_name = "Totally" instance.last_name = "Custom" end end end end it "runs a custom before callback when the proper strategy executes" do expect(FactoryBot.build(:user).name).to eq "John Doe" expect(FactoryBot.custom_before(:user).name).to eq "Overridden First Doe" end it "runs a custom after callback when the proper strategy executes" do expect(FactoryBot.build(:user).name).to eq "John Doe" expect(FactoryBot.custom_after(:user).name).to eq "John Overridden Last" end it "runs a custom callback without prepending before or after when the proper strategy executes" do expect(FactoryBot.build(:user).name).to eq "John Doe" expect(FactoryBot.totally_custom(:user).name).to eq "Totally Custom" end end describe "binding a callback to multiple callbacks" do before do define_model("User", name: :string) FactoryBot.define do factory :user do callback(:before_create, :after_stub) do |instance| instance.name = instance.name.upcase end end end end it "binds the callback to creation" do expect(FactoryBot.create(:user, name: "John Doe").name).to eq "JOHN DOE" end it "does not bind the callback to building" do expect(FactoryBot.build(:user, name: "John Doe").name).to eq "John Doe" end it "binds the callback to stubbing" do expect(FactoryBot.build_stubbed(:user, name: "John Doe").name).to eq "JOHN DOE" end end describe "global callbacks" do include FactoryBot::Syntax::Methods before do define_model("User", name: :string) define_model("Company", name: :string) FactoryBot.define do after :build do |object| object.name = case object.class.to_s when "User" then "John Doe" when "Company" then "Acme Suppliers" end end after :create do |object| object.name = "#{object.name}!!!" end trait :awesome do after :build do |object| object.name = "___#{object.name}___" end after :create do |object| object.name = "A#{object.name}Z" end end factory :user do after :build do |user| user.name = user.name.downcase end end factory :company do after :build do |company| company.name = company.name.upcase end end end end it "triggers after build callbacks for all factories" do expect(build(:user).name).to eq "john doe" expect(create(:user).name).to eq "john doe!!!" expect(create(:user, :awesome).name).to eq "A___john doe___!!!Z" expect(build(:company).name).to eq "ACME SUPPLIERS" end end describe "before build callback" do before do define_class("TitleSetter") do def self.title=(new_title) class_variable_set(:@@title, new_title) end def self.title class_variable_get(:@@title) end end define_model("Article", title: :string) FactoryBot.define do factory :article_with_before_callbacks, class: :article do before(:build) { TitleSetter.title = "title from before build" } after(:build) { TitleSetter.title = "title from after build" } title { TitleSetter.title } end end end it "runs the before callback" do article = FactoryBot.build(:article_with_before_callbacks) expect(article.title).to eq("title from before build") end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/build_spec.rb
spec/acceptance/build_spec.rb
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
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/keyed_by_class_spec.rb
spec/acceptance/keyed_by_class_spec.rb
describe "finding factories keyed by class instead of symbol" do before do define_model("User") do attr_accessor :name, :email end FactoryBot.define do factory :user end end it "doesn't find the factory" do expect { FactoryBot.create(User) }.to( raise_error(KeyError, /Factory not registered: User/) ) end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/nested_attributes_spec.rb
spec/acceptance/nested_attributes_spec.rb
describe "association assignment from nested attributes" do before do define_model("Post", title: :string) do has_many :comments accepts_nested_attributes_for :comments end define_model("Comment", post_id: :integer, body: :text) do belongs_to :post end FactoryBot.define do factory :post do comments_attributes { [FactoryBot.attributes_for(:comment), FactoryBot.attributes_for(:comment)] } end factory :comment do sequence(:body) { |n| "Body #{n}" } end end end it "assigns the correct amount of comments" do expect(FactoryBot.create(:post).comments.count).to eq 2 end it "assigns the correct amount of comments when overridden" do post = FactoryBot.create(:post, comments_attributes: [FactoryBot.attributes_for(:comment)]) expect(post.comments.count).to eq 1 end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/stub_spec.rb
spec/acceptance/stub_spec.rb
describe "a stubbed 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_stubbed(:post) } it "acts as if it came from the database" do should_not be_new_record end it "assigns associations and acts as if it is saved" do expect(subject.user).to be_kind_of(User) expect(subject.user).not_to be_new_record end end describe "a stubbed instance with timestamps" do include FactoryBot::Syntax::Methods before do define_model("ModelWithTimestamps", created_at: :datetime, updated_at: :datetime) FactoryBot.define do factory :model_with_timestamps end end subject { build_stubbed(:model_with_timestamps) } it "assigns the exact same datetime" do expect(subject.created_at).to eq(subject.updated_at) end end describe "a stubbed instance overriding strategy" 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 { build_stubbed(:post) } it "acts as if it is saved in the database" do should_not be_new_record end it "assigns associations and acts as if it is saved" do expect(subject.user).to be_kind_of(User) expect(subject.user).not_to be_new_record end end describe "overridden primary keys conventions" do describe "a stubbed instance with a uuid primary key" do it "builds a stubbed instance" do using_model("ModelWithUuid", primary_key: :uuid) do FactoryBot.define do factory :model_with_uuid end model = FactoryBot.build_stubbed(:model_with_uuid) expect(model).to be_truthy end end it "behaves like a persisted record" do using_model("ModelWithUuid", primary_key: :uuid) do FactoryBot.define do factory :model_with_uuid end model = FactoryBot.build_stubbed(:model_with_uuid) expect(model).to be_persisted expect(model).not_to be_new_record end end it "has a uuid primary key" do using_model("ModelWithUuid", primary_key: :uuid) do FactoryBot.define do factory :model_with_uuid end model = FactoryBot.build_stubbed(:model_with_uuid) expect(model.id).to be_a(String) end end end describe "a stubbed instance with no primary key" do it "builds a stubbed instance" do using_model("ModelWithoutPk", primary_key: false) do FactoryBot.define do factory :model_without_pk end model = FactoryBot.build_stubbed(:model_without_pk) expect(model).to be_truthy end end it "behaves like a persisted record" do using_model("ModelWithoutPk", primary_key: false) do FactoryBot.define do factory :model_without_pk end model = FactoryBot.build_stubbed(:model_without_pk) expect(model).to be_persisted expect(model).not_to be_new_record end end end describe "a stubbed instance with no id setter" do it "builds a stubbed instance" do FactoryBot.define do factory :model_hash, class: Hash end model = FactoryBot.build_stubbed(:model_hash) expect(model).to be_truthy end end def using_model(name, primary_key:) define_class(name, ActiveRecord::Base) connection = ActiveRecord::Base.connection begin clear_generated_table(name.tableize) connection.create_table(name.tableize, id: primary_key) do |t| t.column :updated_at, :datetime end yield ensure clear_generated_table(name.tableize) end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/attributes_from_instance_spec.rb
spec/acceptance/attributes_from_instance_spec.rb
describe "calling methods on the model instance" do before do define_model("User", age: :integer, age_copy: :integer) do def age read_attribute(:age) || 18 end end FactoryBot.define do factory :user do age_copy { age } end end end context "without the attribute being overridden" do it "returns the correct value from the instance" do expect(FactoryBot.build(:user).age_copy).to eq 18 end it "returns nil during attributes_for" do expect(FactoryBot.attributes_for(:user)[:age_copy]).to be_nil end it "doesn't instantiate a record with attributes_for" do allow(User).to receive(:new) FactoryBot.attributes_for(:user) expect(User).to_not have_received(:new) end end context "with the attribute being overridden" do it "uses the overridden value" do expect(FactoryBot.build(:user, age_copy: nil).age_copy).to be_nil end it "uses the overridden value during attributes_for" do expect(FactoryBot.attributes_for(:user, age_copy: 25)[:age_copy]).to eq 25 end end context "with the referenced attribute being overridden" do it "uses the overridden value" do expect(FactoryBot.build(:user, age: nil).age_copy).to be_nil end it "uses the overridden value during attributes_for" do expect(FactoryBot.attributes_for(:user, age: 25)[:age_copy]).to eq 25 end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false