Skip to content

Instantly share code, notes, and snippets.

@jakecraige
Created April 7, 2015 17:19
Show Gist options
  • Save jakecraige/c783ef00dbad04f696e6 to your computer and use it in GitHub Desktop.
Save jakecraige/c783ef00dbad04f696e6 to your computer and use it in GitHub Desktop.
Simple react component testing in rails + capybara
commit 074a79b95e66d999abe500051c5337805575ea3f
Author: Jake Craige <james.craige@gmail.com>
Date: Tue Apr 7 10:14:29 2015 -0700
Add testing infastructure for React components
diff --git a/app/controllers/components_controller.rb b/app/controllers/components_controller.rb
new file mode 100644
index 0000000..4ffc308
--- /dev/null
+++ b/app/controllers/components_controller.rb
@@ -0,0 +1,7 @@
+class ComponentsController < ApplicationController
+ layout false
+
+ def show
+ end
+end
diff --git a/app/views/components/show.html.erb b/app/views/components/show.html.erb
new file mode 100644
index 0000000..cccb724
--- /dev/null
+++ b/app/views/components/show.html.erb
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <%= stylesheet_link_tag :application, media: "all" %>
+ <%= csrf_meta_tags %>
+ </head>
+ <body>
+ <div id="component"></div>
+
+ <%= javascript_include_tag :application %>
+ </body>
+</html>
diff --git a/config/routes.rb b/config/routes.rb
index 9f7d38d..dae96e8 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -53,4 +53,8 @@ Rails.application.routes.draw do
+
+ if Rails.env.test?
+ get "component", to: "components#show"
+ end
end
diff --git a/spec/features/components/match_modal_spec.rb b/spec/features/components/match_modal_spec.rb
new file mode 100644
index 0000000..54f59a2
--- /dev/null
+++ b/spec/features/components/match_modal_spec.rb
@@ -0,0 +1,32 @@
+require 'spec_helper'
+
+feature "MatchModal", :js do
+ it "renders with given data" do
+ props = {
+ matchName: "Jane Doe",
+ userProfilePhotoUrl: "http://example.image/img.jpg",
+ matchProfilePhotoUrl: "http://example.image/img.jpg",
+ similarities: [],
+ messageUrl: "http://localhost/message/1",
+ }
+ render_component("MatchModal", props)
+
+ expect(page).to have_content(
+ I18n.t("connected_modal.congrats", name: props[:matchName])
+ )
+ expect(page).to have_link(
+ I18n.t("connected_modal.say_hi_button"),
+ href: props[:messageUrl],
+ )
+ end
+
+ def render_component(name, props)
+ visit component_path
+ props_json = JSON.dump(props)
+ render_element = <<-JS
+ var element = React.createElement(#{name}, #{props_json});
+ React.render(element, document.getElementById("component"));
+ JS
+ page.evaluate_script(render_element)
+ end
+end
@mcfiredrill
Copy link

This doesn't seem like a good idea

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment