├── lib ├── stimulus_reflex_testing │ ├── version.rb │ └── rspec.rb ├── stimulus_reflex_testing.rb ├── rspec │ └── rails │ │ ├── example │ │ └── reflex_example_group.rb │ │ └── matchers │ │ └── stimulus_reflex.rb └── stimulus_reflex │ ├── test_reflex_patches.rb │ └── test_case.rb ├── .vscode └── settings.json ├── .gitignore ├── .travis.yml ├── test ├── test_helper.rb ├── build_reflex_test.rb └── stimulus_reflex_testing_test.rb ├── bin ├── setup └── console ├── Gemfile ├── Rakefile ├── Gemfile.lock ├── LICENSE.txt ├── stimulus_reflex_testing.gemspec ├── CODE_OF_CONDUCT.md └── README.md /lib/stimulus_reflex_testing/version.rb: -------------------------------------------------------------------------------- 1 | module StimulusReflexTesting 2 | VERSION = "0.3.1" 3 | end 4 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ruby.lint": { 3 | "rubocop": false, 4 | "standard": true 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /_yardoc/ 4 | /coverage/ 5 | /doc/ 6 | /pkg/ 7 | /spec/reports/ 8 | /tmp/ 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | --- 2 | language: ruby 3 | cache: bundler 4 | rvm: 5 | - 2.6.6 6 | before_install: gem install bundler -v 2.1.4 7 | -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | $LOAD_PATH.unshift File.expand_path("../lib", __dir__) 2 | require "stimulus_reflex_testing" 3 | 4 | require "minitest/autorun" 5 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | set -vx 5 | 6 | bundle install 7 | 8 | # Do any other automated setup that you need to do here 9 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | # Specify your gem's dependencies in stimulus_reflex_testing.gemspec 4 | gemspec 5 | 6 | gem "rake", "~> 12.0" 7 | gem "minitest", "~> 5.0" 8 | -------------------------------------------------------------------------------- /lib/stimulus_reflex_testing.rb: -------------------------------------------------------------------------------- 1 | require "stimulus_reflex" 2 | require "stimulus_reflex_testing/version" 3 | require "stimulus_reflex/test_case" 4 | require "stimulus_reflex/test_reflex_patches" 5 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require "bundler/gem_tasks" 2 | require "rake/testtask" 3 | 4 | Rake::TestTask.new(:test) do |t| 5 | t.libs << "test" 6 | t.libs << "lib" 7 | t.test_files = FileList["test/**/*_test.rb"] 8 | end 9 | 10 | task default: :test 11 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | PATH 2 | remote: . 3 | specs: 4 | stimulus_reflex_testing (0.1.0) 5 | 6 | GEM 7 | remote: https://rubygems.org/ 8 | specs: 9 | minitest (5.14.1) 10 | rake (12.3.3) 11 | 12 | PLATFORMS 13 | ruby 14 | 15 | DEPENDENCIES 16 | minitest (~> 5.0) 17 | rake (~> 12.0) 18 | stimulus_reflex_testing! 19 | 20 | BUNDLED WITH 21 | 2.1.4 22 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require "bundler/setup" 4 | require "stimulus_reflex_testing" 5 | 6 | # You can add fixtures and/or initialization code here to make experimenting 7 | # with your gem easier. You can also use a different console, if you like. 8 | 9 | # (If you use this, don't forget to add pry to your Gemfile!) 10 | # require "pry" 11 | # Pry.start 12 | 13 | require "irb" 14 | IRB.start(__FILE__) 15 | -------------------------------------------------------------------------------- /lib/rspec/rails/example/reflex_example_group.rb: -------------------------------------------------------------------------------- 1 | if defined?(StimulusReflex) 2 | module RSpec 3 | module Rails 4 | module ReflexExampleGroup 5 | extend ActiveSupport::Concern 6 | include StimulusReflex::TestCase::Behavior 7 | 8 | module ClassMethods 9 | def reflex_class 10 | described_class 11 | end 12 | end 13 | end 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /lib/stimulus_reflex_testing/rspec.rb: -------------------------------------------------------------------------------- 1 | require "rspec/rails/example/reflex_example_group" 2 | require "rspec/rails/matchers/stimulus_reflex" 3 | 4 | RSpec.configure do |config| 5 | if defined?(StimulusReflex) 6 | config.include Rails.application.routes.url_helpers, type: :reflex 7 | config.include RSpec::Rails::ReflexExampleGroup, type: :reflex 8 | 9 | config.before type: :reflex do 10 | allow_any_instance_of(ActionDispatch::Request).to( 11 | receive(:session).and_return(double(:session, load!: true)) 12 | ) 13 | end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /test/build_reflex_test.rb: -------------------------------------------------------------------------------- 1 | require 'test_helper' 2 | 3 | class BuildReflexTest < MiniTest::Test 4 | class TestReflex < StimulusReflex::Reflex 5 | end 6 | 7 | class TestClass 8 | include StimulusReflex::TestCase::Behavior 9 | def self.reflex_class 10 | TestReflex 11 | end 12 | end 13 | 14 | def test_it_supplies_the_correct_arguments_to_a_reflex 15 | mock = MiniTest::Mock.new 16 | mock.expect(:call, nil, [StimulusReflex::TestCase::TestChannel, Hash]) 17 | 18 | TestReflex.stub(:new, mock) do 19 | TestClass.new.build_reflex(method_name: :create, url: 'http://localhost/url') 20 | end 21 | 22 | mock.verify 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /lib/stimulus_reflex/test_reflex_patches.rb: -------------------------------------------------------------------------------- 1 | module StimulusReflex::TestReflexPatches 2 | def get(instance_variable) 3 | instance_variable_get("@#{instance_variable}") 4 | end 5 | 6 | def run(reflex_method = nil, *args) 7 | reflex_to_run = reflex_method || method_name 8 | 9 | if reflex_to_run 10 | process(reflex_to_run, *args) 11 | else 12 | raise "You must provide the method you want to run for #{self.class.name}" 13 | end 14 | end 15 | 16 | def cable_ready 17 | @cable_ready ||= FableReady.new 18 | end 19 | 20 | class FableReady 21 | def [](key) 22 | self 23 | end 24 | 25 | def method_missing(*) 26 | self 27 | end 28 | 29 | def respond_to_missing?(*) 30 | true 31 | end 32 | end 33 | end 34 | 35 | StimulusReflex::Reflex.include(StimulusReflex::TestReflexPatches) 36 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Jason Charnes 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /stimulus_reflex_testing.gemspec: -------------------------------------------------------------------------------- 1 | require_relative "lib/stimulus_reflex_testing/version" 2 | 3 | Gem::Specification.new do |spec| 4 | spec.name = "stimulus_reflex_testing" 5 | spec.version = StimulusReflexTesting::VERSION 6 | spec.authors = ["Jason Charnes"] 7 | spec.email = ["jason@thecharnes.com"] 8 | 9 | spec.summary = "Write a short summary, because RubyGems requires one." 10 | spec.description = "Write a longer description or delete this line." 11 | spec.homepage = "https://github.com/podia/stimulus_reflex_testing" 12 | spec.license = "MIT" 13 | spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0") 14 | 15 | spec.metadata["homepage_uri"] = spec.homepage 16 | spec.metadata["source_code_uri"] = spec.homepage 17 | # spec.metadata["changelog_uri"] = "Put your gem's CHANGELOG.md URL here." 18 | 19 | # Specify which files should be added to the gem when it is released. 20 | # The `git ls-files -z` loads the files in the RubyGem that have been added into git. 21 | spec.files = Dir.chdir(File.expand_path("..", __FILE__)) do 22 | `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } 23 | end 24 | spec.bindir = "exe" 25 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } 26 | spec.require_paths = ["lib"] 27 | 28 | spec.add_dependency "stimulus_reflex", ">= 3.3.0" 29 | end 30 | -------------------------------------------------------------------------------- /test/stimulus_reflex_testing_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class StimulusReflexTestingTest < Minitest::Test 4 | def test_that_it_has_a_version_number 5 | refute_nil ::StimulusReflexTesting::VERSION 6 | end 7 | 8 | def test_includes_version_number_for_sr_350pre9_and_newer 9 | mock = MiniTest::Mock.new 10 | opts = { channel: 'TestChannel', element: 'TestElement', url: 'https://test.xyz', method_name: 'test' } 11 | 12 | mock.expect(:call, true) do |channel, element:, url:, method_name:, params:, client_attributes:| 13 | assert_equal('3.5.0pre9', client_attributes[:version]) 14 | end 15 | 16 | TestReflexClass.stub(:new, mock) do 17 | TestClass.new.build_reflex(opts, '3.5.0pre9') 18 | end 19 | mock.verify 20 | end 21 | 22 | def test_does_not_include_version_number_for_sr_350pre8_and_older 23 | mock = MiniTest::Mock.new 24 | opts = { channel: 'TestChannel', element: 'TestElement', url: 'https://test.xyz', method_name: 'test' } 25 | 26 | mock.expect(:call, true) do |channel, element:, url:, method_name:, params:, client_attributes:| 27 | assert_nil(client_attributes[:version]) 28 | end 29 | 30 | TestReflexClass.stub(:new, mock) do 31 | TestClass.new.build_reflex(opts, '3.5.0pre8') 32 | end 33 | end 34 | end 35 | 36 | class TestClass 37 | include StimulusReflex::TestCase::Behavior 38 | 39 | def self.reflex_class 40 | TestReflexClass 41 | end 42 | end 43 | 44 | class TestReflexClass 45 | def initialize(channel, url:, element:, method_name:, params:, client_attributes:); true; end 46 | end 47 | -------------------------------------------------------------------------------- /lib/stimulus_reflex/test_case.rb: -------------------------------------------------------------------------------- 1 | require "active_support" 2 | require "active_support/test_case" 3 | 4 | class StimulusReflex::TestCase < ActiveSupport::TestCase 5 | class TestChannel < ActionCable::Channel::TestCase 6 | delegate :env, to: :connection 7 | 8 | def initialize(connection_opts = {}) 9 | super("StimulusReflex::Channel") 10 | @connection = stub_connection(connection_opts.merge(env: {})) 11 | end 12 | 13 | def stream_name 14 | ids = connection.identifiers.map { |identifier| connection.send(identifier).try(:id) || connection.send(identifier) } 15 | [ 16 | "StimulusReflex::Channel", 17 | ids.select(&:present?).join(";") 18 | ].select(&:present?).join(":") 19 | end 20 | end 21 | 22 | module Behavior 23 | extend ActiveSupport::Concern 24 | 25 | def build_reflex(opts = {}, stimulus_reflex_version = StimulusReflex::VERSION) 26 | channel = opts.fetch(:channel, TestChannel.new(opts.fetch(:connection, {}))) 27 | element = opts.fetch(:element, StimulusReflex::Element.new) 28 | version = stimulus_reflex_version 29 | 30 | args_350_pre8 = { element: element, url: opts.fetch(:url, ""), method_name: method_name_from_opts(opts), 31 | params: opts.fetch(:params, {}), client_attributes: {} } 32 | args_350_pre9 = { **args_350_pre8, client_attributes: { version: version } } 33 | 34 | if Gem::Version.new(version) >= Gem::Version.new('3.5.0.rc4') 35 | args_350_rc4 = { reflex_data: StimulusReflex::ReflexData.new({ **args_350_pre8, version: version }) } 36 | self.class.reflex_class.new(channel, **args_350_rc4) 37 | elsif Gem::Version.new(version) > Gem::Version.new('3.5.0pre8') 38 | self.class.reflex_class.new(channel, **args_350_pre9) 39 | else 40 | self.class.reflex_class.new(channel, **args_350_pre8) 41 | end 42 | end 43 | 44 | private 45 | 46 | def method_name_from_opts(opts) 47 | opts.dig(:method_name).to_s.presence 48 | end 49 | end 50 | 51 | include Behavior 52 | rescue NameError => e 53 | if e.missing_name == "ActionCable::Channel::TestCase" 54 | raise "Please install action-cable-testing https://github.com/palkan/action-cable-testing" 55 | else 56 | raise 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /lib/rspec/rails/matchers/stimulus_reflex.rb: -------------------------------------------------------------------------------- 1 | require "rspec/matchers" 2 | 3 | RSpec::Matchers.define :have_set do |instance_variable, expected_value| 4 | match do |actual| 5 | actual.get(instance_variable) == expected_value 6 | end 7 | 8 | description do |actual| 9 | "set #{instance_variable} to #{expected_value}, got #{actual.get(instance_variable)}" 10 | end 11 | end 12 | 13 | RSpec::Matchers.define :broadcast do |**broadcasts| 14 | match do |block| 15 | fable_ready = StimulusReflex::TestReflexPatches::FableReady.new 16 | 17 | allow_any_instance_of(StimulusReflex::CableReadyChannels).to( 18 | receive(:[]).and_return(fable_ready) 19 | ) 20 | 21 | broadcasts.each do |broadcast| 22 | if broadcast.is_a?(Array) 23 | if broadcast[1].present? 24 | expect(fable_ready).to receive(broadcast[0]).with(broadcast[1]).and_return(fable_ready) 25 | else 26 | expect(fable_ready).to receive(broadcast[0]).and_return(fable_ready) 27 | end 28 | else 29 | expect(fable_ready).to receive(broadcast).and_return(fable_ready) 30 | end 31 | end 32 | 33 | block.call 34 | 35 | RSpec::Mocks.verify 36 | end 37 | 38 | def supports_block_expectations? 39 | true 40 | end 41 | end 42 | 43 | RSpec::Matchers.define :morph do |selector| 44 | match do |morphs| 45 | if morphs.is_a?(StimulusReflex::NothingBroadcaster) 46 | return selector.to_s == "nothing" 47 | end 48 | 49 | morph = matching_morph(morphs, selector) 50 | 51 | if morph.present? && @with_chain_called 52 | @content == morph[1] 53 | else 54 | morph 55 | end 56 | end 57 | 58 | description do |morphs| 59 | morph = matching_morph(morphs, selector) 60 | 61 | if @with_chain_called 62 | if !morph 63 | "morph #{selector} but a morph for that selector was not run" 64 | else 65 | "morph #{selector} with #{@content} but the value was: #{morph[1]}" 66 | end 67 | else 68 | "morph #{selector} but a morph for that selector was not run" 69 | end 70 | end 71 | 72 | chain :with do |content| 73 | @with_chain_called = true 74 | @content = content 75 | end 76 | 77 | def supports_block_expectations? 78 | true 79 | end 80 | 81 | def matching_morph(morphs, selector) 82 | if morphs.respond_to?(:call) 83 | morphs.call.find { |morph| morph[0] == selector } 84 | else 85 | morphs.find { |morph| morph[0] == selector } 86 | end 87 | end 88 | 89 | diffable 90 | end 91 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at jason@thecharnes.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [https://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: https://contributor-covenant.org 74 | [version]: https://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # StimulusReflex Testing 2 | 3 | 🚨🚨🚨🚨🚨🚨 **We are no longer maintining this gem.** 🚨🚨🚨🚨🚨🚨 4 | 5 | If you're interested in taking ownership of this project, please reach out. Otherwise we'll likely archive it soon. 6 | 7 | ## Installation 8 | 9 | Add this line to your application's Gemfile: 10 | 11 | ```ruby 12 | gem 'stimulus_reflex_testing' 13 | ``` 14 | 15 | ### Using 5.2 or below? Or using a version of RSpec Rails lower than 4? 16 | 17 | Both Rails 6 and RSpec Rails 4 introduce the `action-cable-testing` library. If you're using Rails 5.2 and a version of RSpec Rails lower than 4, include the `action-cable-testing` gem in your Gemfile. 18 | 19 | ```ruby 20 | gem 'stimulus_reflex_testing' 21 | gem 'action-cable-testing' 22 | ``` 23 | 24 | And then execute: 25 | 26 | $ bundle install 27 | 28 | ### RSpec instructions 29 | 30 | In `spec/rails_helper.rb` make sure to add: `require "stimulus_reflex_testing/rspec"` 31 | 32 | Rspec tests include the reflex testing functionality when `type: :reflex` is provided. If this type is not provided, your Reflex tests won't work. 33 | 34 | ## Usage 35 | 36 | ### `build_reflex` 37 | 38 | To build an instance of your reflex with the required setup handled (channel, url, element, etc) you can use the `build_reflex` method. 39 | 40 | **Note:** In previous versions of the library you didn't have to provide the action you want to test in `build_reflex`. You would build the reflex and then provide the action to the `run` method. Now, the "proper" way to do this is to pass the action as `method_name` to `build_reflex`. 41 | 42 | ```ruby 43 | # With a valid URL so StimulusReflex can build the correct request 44 | build_reflex(method_name: :create, url: posts_url) 45 | 46 | # Does your test rely on a `current_user` (or similar) defined in `ApplicationCable::Connection`? 47 | build_reflex(method_name: :create, url: posts_url, connection: { current_user: create(:user) }) 48 | 49 | # Do you rely on form params? 50 | build_reflex(method_name: :create, url: edit_post_url(post), params: { post: { title: 'A new title!' } }) 51 | 52 | # Need to give your element some data? 53 | reflex = build_reflex(method_name: :create, url: posts_url) 54 | reflex.element.value = "Hello" 55 | reflex.element.dataset.id = "123" 56 | ``` 57 | 58 | ### `#run` 59 | 60 | To unit test a reflex, we provide a method (when using `build_reflex`) called `#run`. This method takes a method name, and any arguments. 61 | 62 | **Note:** The method name is now optional if you provide the action to `build_reflex`, which is now the "correct" way setup your reflex test. 63 | 64 | ```ruby 65 | # Providing the action during setup 66 | reflex = build_reflex(method_name: :create, url: posts_url) 67 | reflex.run 68 | 69 | # Providing the action during setup with arguments 70 | reflex = build_reflex(method_name: :create, url: posts_url) 71 | reflex.run(nil, arg1, arg2) 72 | 73 | # Legacy: Providing the action at "runtime" with arguments 74 | reflex = build_reflex(url: posts_url) 75 | reflex.run(:create, arg1, arg2) 76 | ``` 77 | 78 | **Why does the action need to be in `build_reflex` now?** 79 | 80 | If we wait don't provide the Reflex action until after we've built the reflex, the callbacks do not setup correctly. If you're using callbacks (especially with :only or :except) you may run into issues if you don't provide the action until calling `#run`. 81 | 82 | **Why can't I just call the method directly?** 83 | 84 | You're more than welcome to call the method directly. But, be advised you will lose callbacks. If you need to run `before_reflex` (etc) use the run method. 85 | 86 | _`#run` is a wrapper around the underlying `#process` method in StimulusReflex that runs callbacks._ 87 | 88 | ### `#get` 89 | 90 | To grab an instance variable set by a reflex, you can use the `#get` method when using a reflex built with `build_reflex`. 91 | 92 | ```ruby 93 | # app/reflexes/post_reflex.rb 94 | class PostReflex < ApplicationReflex 95 | def find_post 96 | @post = Post.find(params[:id]) 97 | end 98 | end 99 | 100 | reflex = build_reflex(method_name: :find_post, url: edit_post_url(post), params: { id: post.id }) 101 | reflex.run 102 | reflex.get(:post) #=> returns the @post instance variable 103 | ``` 104 | 105 | ## Matchers 106 | 107 | ### `morph(selector)` 108 | 109 | You can assert that a "run" reflex morphed as you expected: 110 | 111 | ```ruby 112 | # app/reflexes/post_reflex.rb 113 | class PostReflex < ApplicationReflex 114 | def delete 115 | @post = Post.find(params[:id]) 116 | @post.destroy 117 | morph dom_id(@post), "" 118 | end 119 | end 120 | 121 | # spec/reflexes/post_reflex_spec.rb 122 | require 'rails_helper' 123 | 124 | RSpec.describe PostReflex, type: :reflex do 125 | let(:post) { create(:post) } 126 | let(:reflex) { build_reflex(method_name: :delete) } 127 | 128 | describe '#delete' do 129 | it 'morphs the post' do 130 | subject = reflex.run 131 | expect(subject).to morph("#post_#{post.id}") 132 | end 133 | end 134 | end 135 | ``` 136 | 137 | You can also assert the content you provided to morph: 138 | 139 | ```ruby 140 | # spec/reflexes/post_reflex_spec.rb 141 | require 'rails_helper' 142 | 143 | RSpec.describe PostReflex, type: :reflex do 144 | let(:post) { create(:post) } 145 | let(:reflex) { build_reflex(method_name: :delete) } 146 | 147 | describe '#delete' do 148 | it 'morphs the post with an empty string' do 149 | subject = reflex.run 150 | expect(subject).to morph("#post_#{post.id}").with("") 151 | end 152 | end 153 | end 154 | ``` 155 | 156 | You can also run the expecation as a block: 157 | 158 | ```ruby 159 | # spec/reflexes/post_reflex_spec.rb 160 | require 'rails_helper' 161 | 162 | RSpec.describe PostReflex, type: :reflex do 163 | let(:post) { create(:post) } 164 | let(:reflex) { build_reflex(method_name: :delete) } 165 | 166 | describe '#delete' do 167 | it 'morphs the post with an empty string' do 168 | expect { reflex.run }.to morph("#post_#{post.id}").with("") 169 | end 170 | end 171 | end 172 | ``` 173 | 174 | ### `broadcast(operations)` (Experimental) 175 | 176 | You can assert that a reflex will perform the CableReady operations you anticipate: 177 | 178 | ```ruby 179 | # app/reflexes/post_reflex.rb 180 | class PostReflex < ApplicationReflex 181 | def delete 182 | @post = Post.find(params[:id]) 183 | @post.destroy 184 | cable_ready[PostsChannel].remove(selector: dom_id(@post)).broadcast 185 | end 186 | end 187 | 188 | # spec/reflexes/post_reflex_spec.rb 189 | require 'rails_helper' 190 | 191 | RSpec.describe PostReflex, type: :reflex do 192 | let(:post) { create(:post) } 193 | let(:reflex) { build_reflex(method_name: :delete) } 194 | 195 | describe '#delete' do 196 | it 'broadcasts the CableReady operations' do 197 | expect { reflex }.to broadcast(:remove, :broadcast) 198 | end 199 | 200 | it 'removes the post' do 201 | expect { reflex }.to broadcast(remove: { selector: "#post_#{post.id}" }, broadcast: nil) 202 | end 203 | end 204 | end 205 | ``` 206 | 207 | ## RSpec example 208 | 209 | ```ruby 210 | # app/reflexes/post_reflex.rb 211 | class PostReflex < ApplicationReflex 212 | def validate 213 | @post = Post.find(element.dataset.post_id) 214 | @post.validate 215 | end 216 | end 217 | 218 | # spec/reflexes/post_reflex_spec.rb 219 | require 'rails_helper' 220 | 221 | RSpec.describe PostReflex, type: :reflex do 222 | let(:post) { create(:post) } 223 | let(:reflex) { build_reflex(method_name: :validate, url: edit_post_url(post)) } 224 | 225 | describe '#validate' do 226 | subject { reflex.run } 227 | 228 | before do 229 | reflex.element.dataset.post_id = post.id 230 | subject 231 | end 232 | 233 | it 'finds the post' do 234 | expect(reflex.get(:post)).to eq(post) 235 | end 236 | 237 | it 'validates the post' do 238 | expect(reflex.get(:post).errors).to be_present 239 | end 240 | end 241 | end 242 | ``` 243 | 244 | ## Development 245 | 246 | After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. 247 | 248 | To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). 249 | 250 | ## Contributing 251 | 252 | Bug reports and pull requests are welcome on GitHub at https://github.com/podia/stimulus_reflex_testing. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/podia/stimulus_reflex_testing/blob/master/CODE_OF_CONDUCT.md). 253 | 254 | ## License 255 | 256 | The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). 257 | 258 | ## Code of Conduct 259 | 260 | Everyone interacting in the StimulusReflexTesting project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/podia/stimulus_reflex_testing/blob/master/CODE_OF_CONDUCT.md). 261 | --------------------------------------------------------------------------------