Share
Embed
Transcript
105 slides
-
Why is RSpec complicated? •RSpec is expressive •And very flexible
•And it’s a big library -
This flexible… RSpec.! Hotel do " "works" do #(1 +
1).to ❤(2) end end -
Once upon a time, there was a test… require 'rails_helper'
RSpec.describe Name do it "produces a sort name" do name = Name.new("Noel", "Rappin") expect(name.sort_name).to eq("Rappin, Noel") end end -
RSpec with Parentheses require 'rails_helper' RSpec.describe(Name) do self.it(“produces a
sort name”) do name = Name.new("Noel", "Rappin") self.expect(name.sort_name).to(self.eq(“Rappin, Noel”)) end end -
Key RSpec words require 'rails_helper' RSpec.describe(Name) do self.it(“produces a
sort name”) do name = Name.new("Noel", "Rappin") self.expect(name.sort_name).to(self.eq(“Rappin, Noel”)) end end -
require 'rails_helper' RSpec.describe(Name) do self.it(“produces a sort name”) do
name = Name.new("Noel", "Rappin") self.expect(name.sort_name).to(self.eq(“Rappin, Noel”)) end end -
require 'rails_helper' RSpec.describe(Name) do self.it(“produces a sort name”) do
name = Name.new("Noel", "Rappin") self.expect(name.sort_name).to(self.eq(“Rappin, Noel”)) end end Example Group -
require 'rails_helper' RSpec.describe(Name) do self.it(“produces a sort name”) do
name = Name.new("Noel", "Rappin") self.expect(name.sort_name).to(self.eq(“Rappin, Noel”)) end end Example Group Example -
require 'rails_helper' RSpec.describe(Name) do self.it(“produces a sort name”) do
name = Name.new("Noel", "Rappin") self.expect(name.sort_name).to(self.eq(“Rappin, Noel”)) end end Example Group Example ExpectationTarget -
require 'rails_helper' RSpec.describe(Name) do self.it(“produces a sort name”) do
name = Name.new("Noel", "Rappin") self.expect(name.sort_name).to(self.eq(“Rappin, Noel”)) end end Example Group Example ExpectationTarget Matcher -
Example Group • Created by describe or context • Arguments
are a description, metadata, and block • Creates an anonymous subclass of ExampleGroup • Executes the block in the context of the class RSpec.describe Name, metadata: true do #stuff end -
Creating an ExampleGroup def self.subclass(parent, description, args, &example_group_block) subclass =
Class.new(parent) subclass.set_it_up(description, *args, &example_group_block) subclass.module_exec(&example_group_block) if example_group_block MemoizedHelpers.define_helpers_on(subclass) subclass end -
Example Group Subclass def self.subclass(parent, description, args, &example_group_block) subclass =
Class.new(parent) subclass.set_it_up(description, *args, &example_group_block) subclass.module_exec(&example_group_block) if example_group_block MemoizedHelpers.define_helpers_on(subclass) subclass end -
Setup (configure mock package) def self.subclass(parent, description, args, &example_group_block) subclass
= Class.new(parent) subclass.set_it_up(description, *args, &example_group_block) subclass.module_exec(&example_group_block) if example_group_block MemoizedHelpers.define_helpers_on(subclass) subclass end -
Setup (configure mock package) def self.subclass(parent, description, args, &example_group_block) subclass
= Class.new(parent) subclass.set_it_up(description, *args, &example_group_block) subclass.module_exec(&example_group_block) if example_group_block MemoizedHelpers.define_helpers_on(subclass) subclass end -
Setup (configure mock package) def self.subclass(parent, description, args, &example_group_block) subclass
= Class.new(parent) subclass.set_it_up(description, *args, &example_group_block) subclass.module_exec(&example_group_block) if example_group_block MemoizedHelpers.define_helpers_on(subclass) subclass end -
What is module_exec? class Thing end Thing.module_exec(arg) do |arg|
def hello() "Hello there!" end end puts Thing.new.hello() -
Minimal RSpec with Parentheses require 'rails_helper' <<ExampleGroupSubclass>>.module_exec do it(“produces
a sort name”) do name = Name.new("Noel", "Rappin") expect(name.sort_name).to(eq(“Rappin, Noel”)) end end -
Example • Created by it, example, specify — instance methods
of ExampleGroup • Arguments are description, metadata, and a block • Assigns the example to an array class attribute of the ExampleGroup it(“produces a sort name”) do #stuff end -
Creating an Example desc, *args = *all_args options = Metadata.build_hash_from(args)
unless block options.update(:skip => RSpec::Core::Pending::NOT_YET_IMPLEMENTED) end options.update(extra_options) examples << RSpec::Core::Example.new(self, desc, options, block) examples.last -
Creating an Example desc, *args = *all_args options = Metadata.build_hash_from(args)
unless block options.update(:skip => RSpec::Core::Pending::NOT_YET_IMPLEMENTED) end options.update(extra_options) examples << RSpec::Core::Example.new(self, desc, options, block) examples.last -
Creating an Example desc, *args = *all_args options = Metadata.build_hash_from(args)
unless block options.update(:skip => RSpec::Core::Pending::NOT_YET_IMPLEMENTED) end options.update(extra_options) examples << RSpec::Core::Example.new(self, desc, options, block) examples.last -
What happens at run time? •RSpec creates an instance of
the anonymous ExampleGroup class •The new instance runs all of its examples -
Running an Example Group def self.run(reporter=RSpec::Core::NullReporter) return if RSpec.world.wants_to_quit reporter.example_group_started(self)
should_run_context_hooks = descendant_filtered_examples.any? begin run_before_context_hooks(new('before(:context) hook')) if should_run_context_hooks result_for_this_group = run_examples(reporter) results_for_descendants = ordering_strategy.order(children).map { |child| child.run(reporter) }.all? result_for_this_group && results_for_descendants rescue Pending::SkipDeclaredInExample => ex for_filtered_examples(reporter) { |example| example.skip_with_exception(reporter, ex) } true rescue Exception => ex RSpec.world.wants_to_quit = true if fail_fast? for_filtered_examples(reporter) { |example| example.fail_with_exception(reporter, ex) } false ensure run_after_context_hooks(new('after(:context) hook')) if should_run_context_hooks reporter.example_group_finished(self) end end -
Running an Example Group def self.run(reporter=RSpec::Core::NullReporter) return if RSpec.world.wants_to_quit reporter.example_group_started(self)
should_run_context_hooks = descendant_filtered_examples.any? -
Running an Example Group begin run_before_context_hooks(new('before(:context) hook')) if should_run_context_hooks result_for_this_group
= run_examples(reporter) results_for_descendants = ordering_strategy.order(children).map { |child| child.run(reporter) }.all? result_for_this_group && results_for_descendants -
Running an Example Group rescue Pending::SkipDeclaredInExample => ex for_filtered_examples(reporter)
{ |example| example.skip_with_exception(reporter, ex) } true rescue Exception => ex RSpec.world.wants_to_quit = true if fail_fast? for_filtered_examples(reporter) { |example| example.fail_with_exception(reporter, ex) } false -
Running an Example Group ensure run_after_context_hooks(new('after(:context) hook')) if should_run_context_hooks
reporter.example_group_finished(self) end end -
Running an Example Group def self.run(reporter=RSpec::Core::NullReporter) return if RSpec.world.wants_to_quit reporter.example_group_started(self)
should_run_context_hooks = descendant_filtered_examples.any? begin run_before_context_hooks(new('before(:context) hook')) if should_run_context_hooks result_for_this_group = run_examples(reporter) results_for_descendants = ordering_strategy.order(children).map { |child| child.run(reporter) }.all? result_for_this_group && results_for_descendants rescue Pending::SkipDeclaredInExample => ex for_filtered_examples(reporter) { |example| example.skip_with_exception(reporter, ex) } true rescue Exception => ex RSpec.world.wants_to_quit = true if fail_fast? for_filtered_examples(reporter) { |example| example.fail_with_exception(reporter, ex) } false ensure run_after_context_hooks(new('after(:context) hook')) if should_run_context_hooks reporter.example_group_finished(self) end end -
Running Examples def self.run_examples(reporter) ordering_strategy.order(filtered_examples).map do |example| next if RSpec.world.wants_to_quit
instance = new(example.inspect_output) set_ivars(instance, before_context_ivars) succeeded = example.run(instance, reporter) RSpec.world.wants_to_quit = true if fail_fast? && !succeeded succeeded end.all? end -
Running Examples def self.run_examples(reporter) ordering_strategy.order(filtered_examples).map do |example| next if RSpec.world.wants_to_quit
instance = new(example.inspect_output) set_ivars(instance, before_context_ivars) succeeded = example.run(instance, reporter) RSpec.world.wants_to_quit = true if fail_fast? && !succeeded succeeded end.all? end -
Running Examples def self.run_examples(reporter) ordering_strategy.order(filtered_examples).map do |example| next if RSpec.world.wants_to_quit
instance = new(example.inspect_output) set_ivars(instance, before_context_ivars) succeeded = example.run(instance, reporter) RSpec.world.wants_to_quit = true if fail_fast? && !succeeded succeeded end.all? end -
Running Examples def self.run_examples(reporter) ordering_strategy.order(filtered_examples).map do |example| next if RSpec.world.wants_to_quit
instance = new(example.inspect_output) set_ivars(instance, before_context_ivars) succeeded = example.run(instance, reporter) RSpec.world.wants_to_quit = true if fail_fast? && !succeeded succeeded end.all? end -
Running Examples def self.run_examples(reporter) ordering_strategy.order(filtered_examples).map do |example| next if RSpec.world.wants_to_quit
instance = new(example.inspect_output) set_ivars(instance, before_context_ivars) succeeded = example.run(instance, reporter) RSpec.world.wants_to_quit = true if fail_fast? && !succeeded succeeded end.all? end -
Running Examples def self.run_examples(reporter) ordering_strategy.order(filtered_examples).map do |example| next if RSpec.world.wants_to_quit
instance = new(example.inspect_output) set_ivars(instance, before_context_ivars) succeeded = example.run(instance, reporter) RSpec.world.wants_to_quit = true if fail_fast? && !succeeded succeeded end.all? end -
Running Examples def self.run_examples(reporter) ordering_strategy.order(filtered_examples).map do |example| next if RSpec.world.wants_to_quit
instance = new(example.inspect_output) set_ivars(instance, before_context_ivars) succeeded = example.run(instance, reporter) RSpec.world.wants_to_quit = true if fail_fast? && !succeeded succeeded end.all? end -
Running One Example • Check that it is not pending
• Run before blocks • instance_exec the block in the context of the example group • Raise is the example skips or fails • Run after blocks -
begin run_before_example @example_group_instance.instance_exec(self, &@example_block) if pending? Pending.mark_fixed! self raise Pending::PendingExampleFixedError,
'Expected example to fail since it is pending, but it passed.', [location] end rescue Pending::SkipDeclaredInExample # no-op, required metadata has already been set by the `skip` # method. rescue Exception => e set_exception(e) ensure run_after_example finish(reporter) end -
begin run_before_example @example_group_instance.instance_exec(self, &@example_block) if pending? Pending.mark_fixed! self raise Pending::PendingExampleFixedError,
'Expected example to fail since it is pending, but it passed.', [location] end rescue Pending::SkipDeclaredInExample # no-op, required metadata has already been set by the `skip` # method. rescue Exception => e set_exception(e) ensure run_after_example finish(reporter) end -
begin run_before_example @example_group_instance.instance_exec(self, &@example_block) if pending? Pending.mark_fixed! self raise Pending::PendingExampleFixedError,
'Expected example to fail since it is pending, but it passed.', [location] end rescue Pending::SkipDeclaredInExample # no-op, required metadata has already been set by the `skip` # method. rescue Exception => e set_exception(e) ensure run_after_example finish(reporter) end -
begin run_before_example @example_group_instance.instance_exec(self, &@example_block) if pending? Pending.mark_fixed! self raise Pending::PendingExampleFixedError,
'Expected example to fail since it is pending, but it passed.', [location] end rescue Pending::SkipDeclaredInExample # no-op, required metadata has already been set by the `skip` # method. rescue Exception => e set_exception(e) ensure run_after_example finish(reporter) end -
begin run_before_example @example_group_instance.instance_exec(self, &@example_block) if pending? Pending.mark_fixed! self raise Pending::PendingExampleFixedError,
'Expected example to fail since it is pending, but it passed.', [location] end rescue Pending::SkipDeclaredInExample # no-op, required metadata has already been set by the `skip` # method. rescue Exception => e set_exception(e) ensure run_after_example finish(reporter) end -
begin run_before_example @example_group_instance.instance_exec(self, &@example_block) if pending? Pending.mark_fixed! self raise Pending::PendingExampleFixedError,
'Expected example to fail since it is pending, but it passed.', [location] end rescue Pending::SkipDeclaredInExample # no-op, required metadata has already been set by the `skip` # method. rescue Exception => e set_exception(e) ensure run_after_example finish(reporter) end -
eq is a built in method of RSpec::Matchers def eq(expected)
BuiltIn::Eq.new(expected) end -
BE_PREDICATE_REGEX = /^(be_(?:an?_)?)(.*)/ HAS_REGEX = /^(?:have_)(.*)/ def method_missing(method, *args,
&block) case method.to_s when BE_PREDICATE_REGEX BuiltIn::BePredicate.new(method, *args, &block) when HAS_REGEX BuiltIn::Has.new(method, *args, &block) else super end end -
class BePredicate < BaseMatcher include BeHelpers def initialize(*args, &block)
@expected = parse_expected(args.shift) @args = args @block = block end def matches?(actual, &block) @actual = actual @block ||= block predicate_accessible? && predicate_matches? end def predicate_accessible? actual.respond_to?(predicate) || actual.respond_to?(present_tense_predicate) end def predicate_matches? method_name = actual.respond_to?(predicate) ? predicate : present_tense_predicate @predicate_matches = actual.__send__(method_name, *@args, &@block) end end -
def matches?(actual, &block) @actual = actual @block ||=
block predicate_accessible? && predicate_matches? end def predicate_accessible? actual.respond_to?(predicate) || actual.respond_to?(present_tense_predicate) end def predicate_matches? method_name = actual.respond_to?(predicate) ? predicate : present_tense_predicate @predicate_matches = actual.__send__(method_name, *@args, &@block) end -
def matches?(actual, &block) @actual = actual @block ||=
block predicate_accessible? && predicate_matches? end def predicate_accessible? actual.respond_to?(predicate) || actual.respond_to?(present_tense_predicate) end def predicate_matches? method_name = actual.respond_to?(predicate) ? predicate : present_tense_predicate @predicate_matches = actual.__send__(method_name, *@args, &@block) end -
def matches?(actual, &block) @actual = actual @block ||=
block predicate_accessible? && predicate_matches? end def predicate_accessible? actual.respond_to?(predicate) || actual.respond_to?(present_tense_predicate) end def predicate_matches? method_name = actual.respond_to?(predicate) ? predicate : present_tense_predicate @predicate_matches = actual.__send__(method_name, *@args, &@block) end -
def matches?(actual, &block) @actual = actual @block ||=
block predicate_accessible? && predicate_matches? end def predicate_accessible? actual.respond_to?(predicate) || actual.respond_to?(present_tense_predicate) end def predicate_matches? method_name = actual.respond_to?(predicate) ? predicate : present_tense_predicate @predicate_matches = actual.__send__(method_name, *@args, &@block) end -
define_example_group_method :example_group define_example_group_method :describe define_example_group_method :context define_example_group_method :xdescribe, :skip =>
"Temporarily skipped with xdescribe" define_example_group_method :xcontext, :skip => "Temporarily skipped with xcontext" define_example_group_method :fdescribe, :focus => true define_example_group_method :fcontext, :focus => true -
define_example_method :specify define_example_method :focus, :focus => true define_example_method :fexample, :focus
=> true define_example_method :fit, :focus => true define_example_method :fspecify, :focus => true define_example_method :xexample, :skip => 'Temporarily skipped with xexample' define_example_method :xit, :skip => 'Temporarily skipped with xit' define_example_method :skip, :skip => true define_example_method :pending, :pending => true -
require 'rails_helper' module RSpec module Core class ExampleGroup define_example_group_method
:! define_example_method :" end end module Matchers def #(value=::RSpec::Expectations::ExpectationTarget::UndefinedValue, &block) ::RSpec::Expectations::ExpectationTarget.for(value, block) end alias_matcher :❤, :eq end end -
And then… RSpec.! Hotel do " "works" do #(1 +
1).to ❤(2) end end -
Simple Mock Example require 'rails_helper' RSpec.describe Name do it
"assigns a rating category" do user = User.new() expect(user).to receive(:credit_rating).and_return(1000) expect(user.rating_category).to eq("approved") end end -
What would this mock need to do? •Ensure the method
is not called •Track how often it’s called •Verify that expectations are met -
Ruby Method Lookup path • Singleton class • instance methods
of class • Included modules • parent of class • parent’s included modules • and so on… -
Singleton Class class << x def foo #something end end
def x.bar #something end x.foo; x.bar -
Key Concepts • Receive is a matcher • Space •
Proxy • Method Double Original Object Singleton Class MethodDouble Proxy Space Receive Matcher -
Inside the Receive Matcher def setup_expectation(subject, &block) warn_if_any_instance("expect", subject) @describable
= setup_mock_proxy_method_substitute( subject, :add_message_expectation, block) end alias matches? setup_expectation def setup_mock_proxy_method_substitute(subject, method, block) proxy = ::RSpec::Mocks.space.proxy_for(subject) setup_method_substitute(proxy, method, block) end -
Inside the Receive Matcher def setup_expectation(subject, &block) warn_if_any_instance("expect", subject) @describable
= setup_mock_proxy_method_substitute( subject, :add_message_expectation, block) end alias matches? setup_expectation def setup_mock_proxy_method_substitute(subject, method, block) proxy = ::RSpec::Mocks.space.proxy_for(subject) setup_method_substitute(proxy, method, block) end -
Inside the Receive Matcher def setup_expectation(subject, &block) warn_if_any_instance("expect", subject) @describable
= setup_mock_proxy_method_substitute( subject, :add_message_expectation, block) end alias matches? setup_expectation def setup_mock_proxy_method_substitute(subject, method, block) proxy = ::RSpec::Mocks.space.proxy_for(subject) setup_method_substitute(proxy, method, block) end -
Inside the Receive Matcher def setup_expectation(subject, &block) warn_if_any_instance("expect", subject) @describable
= setup_mock_proxy_method_substitute( subject, :add_message_expectation, block) end alias matches? setup_expectation def setup_mock_proxy_method_substitute(subject, method, block) proxy = ::RSpec::Mocks.space.proxy_for(subject) setup_method_substitute(proxy, method, block) end -
Proxy adds Expectations def add_message_expectation(method_name, opts={}, &block) location = opts.fetch(:expected_from)
{ CallerFilter.first_non_rspec_line } meth_double = method_double_for(method_name) if null_object? && !block meth_double.add_default_stub(@error_generator, @order_group, location, opts) do @object end end meth_double.add_expectation @error_generator, @order_group, location, opts, &block end -
Proxy adds Expectations def add_message_expectation(method_name, opts={}, &block) location = opts.fetch(:expected_from)
{ CallerFilter.first_non_rspec_line } meth_double = method_double_for(method_name) if null_object? && !block meth_double.add_default_stub(@error_generator, @order_group, location, opts) do @object end end meth_double.add_expectation @error_generator, @order_group, location, opts, &block end -
Proxy adds Expectations def add_message_expectation(method_name, opts={}, &block) location = opts.fetch(:expected_from)
{ CallerFilter.first_non_rspec_line } meth_double = method_double_for(method_name) if null_object? && !block meth_double.add_default_stub(@error_generator, @order_group, location, opts) do @object end end meth_double.add_expectation @error_generator, @order_group, location, opts, &block end -
Method Double def define_proxy_method return if @method_is_proxied save_original_method! definition_target.class_exec( self,
method_name, visibility) do |method_double, method_name, visibility| define_method(method_name) do |*args, &block| method_double.proxy_method_invoked(self, *args, &block) end __send__(visibility, method_name) end @method_is_proxied = true end def proxy_method_invoked(_obj, *args, &block) @proxy.message_received method_name, *args, &block end -
Method Double def define_proxy_method return if @method_is_proxied save_original_method! definition_target.class_exec( self,
method_name, visibility) do |method_double, method_name, visibility| define_method(method_name) do |*args, &block| method_double.proxy_method_invoked(self, *args, &block) end __send__(visibility, method_name) end @method_is_proxied = true end def proxy_method_invoked(_obj, *args, &block) @proxy.message_received method_name, *args, &block end -
Method Double def define_proxy_method return if @method_is_proxied save_original_method! definition_target.class_exec( self,
method_name, visibility) do |method_double, method_name, visibility| define_method(method_name) do |*args, &block| method_double.proxy_method_invoked(self, *args, &block) end __send__(visibility, method_name) end @method_is_proxied = true end def proxy_method_invoked(_obj, *args, &block) @proxy.message_received method_name, *args, &block end -
Method Double def define_proxy_method return if @method_is_proxied save_original_method! definition_target.class_exec( self,
method_name, visibility) do |method_double, method_name, visibility| define_method(method_name) do |*args, &block| method_double.proxy_method_invoked(self, *args, &block) end __send__(visibility, method_name) end @method_is_proxied = true end def proxy_method_invoked(_obj, *args, &block) @proxy.message_received method_name, *args, &block end -
Method Double def define_proxy_method return if @method_is_proxied save_original_method! definition_target.class_exec( self,
method_name, visibility) do |method_double, method_name, visibility| define_method(method_name) do |*args, &block| method_double.proxy_method_invoked(self, *args, &block) end __send__(visibility, method_name) end @method_is_proxied = true end def proxy_method_invoked(_obj, *args, &block) @proxy.message_received method_name, *args, &block end -
Noel Rappin Table XI @noelrap http://www.pragprog.com/book/nrtest2 (test2rappin for 25% off)
http://www.noelrappin.com/trdd http://www.noelrappin.com/mstwjs