From 08a200b13843bfebe55a84208f0a00a34977e3c2 Mon Sep 17 00:00:00 2001 From: Joshua Clayton Date: Fri, 5 Jun 2015 14:16:13 -0400 Subject: [PATCH] Allow RSpec view specs to leverage Capybara matchers Capybara provides a number of helpful matchers for asserting against a DOM structure with various selectors. RSpec's view specs focus on asserting against specific markup; this change ensures this is easier to do. RSpec.describe "todos/show.html.erb", type: :view do it "displays the todo title" do assign :todo, Todo.new(title: "Buy milk") render # without Capybara matchers - potentially ambiguous, doesn't # test markup, only raw text rendered expect(rendered).to contain "Buy milk" # with Capybara matchers expect(rendered).to have_css("header h1", text: "Buy milk") end end --- README.md | 16 +++++++++++++++- lib/capybara/rspec.rb | 1 + spec/rspec/views_spec.rb | 7 +++++++ 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 spec/rspec/views_spec.rb diff --git a/README.md b/README.md index 312b6e2a..256f51c8 100644 --- a/README.md +++ b/README.md @@ -167,7 +167,7 @@ describe 'some stuff which requires js', :js => true do end ``` -Finally, Capybara also comes with a built in DSL for creating descriptive acceptance tests: +Capybara also comes with a built in DSL for creating descriptive acceptance tests: ```ruby feature "Signing in" do @@ -203,6 +203,20 @@ end `background` is an alias for `before`, `scenario` for `it`, and `given`/`given!` aliases for `let`/`let!`, respectively. +Finally, Capybara matchers are supported in view specs: + +```ruby +RSpec.describe "todos/show.html.erb", type: :view do + it "displays the todo title" do + assign :todo, Todo.new(title: "Buy milk") + + render + + expect(rendered).to have_css("header h1", text: "Buy milk") + end +end +``` + ## Using Capybara with Test::Unit * If you are using Rails, add the following code in your `test_helper.rb` diff --git a/lib/capybara/rspec.rb b/lib/capybara/rspec.rb index cba5009d..f06603bf 100644 --- a/lib/capybara/rspec.rb +++ b/lib/capybara/rspec.rb @@ -7,6 +7,7 @@ require 'capybara/rspec/features' RSpec.configure do |config| config.include Capybara::DSL, :type => :feature config.include Capybara::RSpecMatchers, :type => :feature + config.include Capybara::RSpecMatchers, :type => :view # A work-around to support accessing the current example that works in both # RSpec 2 and RSpec 3. diff --git a/spec/rspec/views_spec.rb b/spec/rspec/views_spec.rb new file mode 100644 index 00000000..c9ae8cb0 --- /dev/null +++ b/spec/rspec/views_spec.rb @@ -0,0 +1,7 @@ +require 'spec_helper' + +RSpec.describe "capybara/rspec", type: :view do + it "allows matchers to be used on strings" do + expect(%{

Test header

}).to have_css("h1", text: "Test header") + end +end