I am trying to write a simple spec with Capybara using the Poltergeist driver in RSpec. There doesn't seem to be a problem when tests should fail , however when I am expecting a passing test I get the following error:
~/.rbenv/versions/2.2.3/lib/
ruby/gems/2.2.0/gems/poltergeist-1.6.0/lib/capybara/poltergeist/errors.rb:17:in
`initialize': wrong number of arguments (0 for 2) (ArgumentError)
I navigated to where the the line of code the error was indicating:
class JSErrorItem
attr_reader :message, :stack
def initialize(message, stack)
#message = message
#stack = stack
end
def to_s
[message, stack].join("\n")
end
end
But I was unable to find anywhere that I should be interacting with this constructor.
This is the spec that I am writing
describe 'Sign Up', type: :feature do
it 'should allow user creation through the signup form' do
visit new_user_url host: 'http://localhost:3000'
within('.form') do
fill_in('user[username]', with: 'Example')
fill_in('user[password]', with: 'Password')
fill_in('user[password_confirmation]', with: 'Password')
find(".submit-button").click
puts page.body
expect(page).to have_content('Welcome')
User.last.destroy!
end
end
end
The puts page prints the content of the page as expected but after the error occurs and the remainder of the lines in the spec are not run. Oddly enough the error only occurs when I am expecting the spec to pass. When I am expecting a failing test the entire spec runs without error.
My spec helper was set up as below:
RSpec.configure do |config|
require 'capybara/rspec'
require 'capybara/poltergeist'
require 'capybara/dsl'
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, time_out: 120, phantomjs_options: ['--ignore-ssl-errors=yes'], js_errors: false)
end
Capybara.configure do |c|
c.javascript_driver = :poltergeist
c.default_driver = :poltergeist
c.app_host = 'http://localhost:3000'
end
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
I upgraded Poltergeist to 1.9 and PhantomJS to 2.1 as suggested in the comments and it fixed the issue.
Related
I'm working on updating a rails 3.2 app to rails 4.2.10, I've got almost everything worked out, unit tests and integration tests passing.
I'm having some issues with feature tests, I'm using capybara 3.3.0 and poltergeist 1.18.1 and it throws me error on visit '/'
I've looked at lots of issues on Stack regarding Attemped to assign to readonly property but none of them apply to my case here,
This is my stripped down spec file
require 'vcr'
Capybara.default_max_wait_time = 10
feature "Create something" do
include SpecHelpers
include Acceptance
before do
setup_database
end
after do
teardown_database
end
scenario "Creating a Consignment", :js => true do
puts "Running with #{Capybara.current_driver}"
VCR.use_cassette('cassette_name.yml') do
page.driver.resize(1000,2200) unless Capybara.current_driver == :selenium
visit '/'
expect(page).to have_content 'EMAIL'
expect(page).to have_content 'PASSWORD'
end
end
end
This is my stripped down spec helper file
ENV["RAILS_ENV"] ||= 'test'
require_relative '../config/environment.rb'
require 'rspec/rails'
require 'capybara/rails'
require 'capybara/poltergeist'
require 'shoulda/matchers'
require 'redis'
require 'redis-namespace'
require 'resque'
require 'mock_redis'
require 'bcrypt'
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
# rspec
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end
RSpec.configure do |config|
config.deprecation_stream = 'log/deprecations.log'
end
RSpec.configure do |config|
config.include Devise::Test::ControllerHelpers, :type => :controller
end
RSpec::Expectations.configuration.on_potential_false_positives = :nothing
BCrypt::Engine.cost = 1
if (ENV['DEBUG_CAP'])
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, :browser => :chrome)
end
else
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, {js_errors: true})
end
Capybara.javascript_driver = :poltergeist
end
Capybara.server_port = 31337
Capybara.server = :webrick
module SpecHelpers
def setup_database
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.start
end
def teardown_database
DatabaseCleaner.clean
end
end
module Acceptance
VCR.configure do |c|
require 'webmock'
c.hook_into :webmock
c.cassette_library_dir = 'fixtures/vcr_cassettes'
c.allow_http_connections_when_no_cassette = true
c.default_cassette_options = {:record => :new_episodes}
c.ignore_request do |request|
URI(request.uri).port == Capybara.server_port || request.uri=~/shutdown/ || request.uri=~/session/
end
end
def wait_until(timeout = Capybara.default_max_wait_time)
require "timeout"
begin
Timeout.timeout(timeout) do
sleep(0.3) until value = yield
value
end
rescue => e
save_screenshot "capybara_#{Time.now.to_i}.png"
puts e.message
puts e.backtrace
raise e
end
end
end
require "rspec/mocks/standalone"
....
This is the error stack trace
Running with poltergeist
Error: Attempted to assign to readonly property.
r#http://127.0.0.1:31337/lib/bfd57c67.components.js:22:3139
r#http://127.0.0.1:31337/lib/bfd57c67.components.js:5:3551
http://127.0.0.1:31337/lib/bfd57c67.components.js:5:19730
http://127.0.0.1:31337/lib/bfd57c67.components.js:5:12707
s#http://127.0.0.1:31337/lib/bfd57c67.components.js:4:20964
g#http://127.0.0.1:31337/lib/bfd57c67.components.js:5:12573
http://127.0.0.1:31337/lib/bfd57c67.components.js:5:16265
http://127.0.0.1:31337/lib/bfd57c67.components.js:5:22205
c#http://127.0.0.1:31337/lib/bfd57c67.components.js:6:4206
c#http://127.0.0.1:31337/lib/bfd57c67.components.js:6:4206
http://127.0.0.1:31337/lib/bfd57c67.components.js:6:4884
$digest#http://127.0.0.1:31337/lib/bfd57c67.components.js:6:7801
$apply#http://127.0.0.1:31337/lib/bfd57c67.components.js:6:9410
http://127.0.0.1:31337/lib/bfd57c67.components.js:4:26430
a#http://127.0.0.1:31337/lib/bfd57c67.components.js:4:26340
Z#http://127.0.0.1:31337/lib/bfd57c67.components.js:4:26051
http://127.0.0.1:31337/lib/bfd57c67.components.js:7:28112
d#http://127.0.0.1:31337/lib/bfd57c67.components.js:1:18351
fireWith#http://127.0.0.1:31337/lib/bfd57c67.components.js:1:19152
ready#http://127.0.0.1:31337/lib/bfd57c67.components.js:1:13970
wt#http://127.0.0.1:31337/lib/bfd57c67.components.js:1:11347
Error: Attempted to assign to readonly property.
r#http://127.0.0.1:31337/lib/bfd57c67.components.js:22:3139
r#http://127.0.0.1:31337/lib/bfd57c67.components.js:5:3551
http://127.0.0.1:31337/lib/bfd57c67.components.js:5:19730
http://127.0.0.1:31337/lib/bfd57c67.components.js:5:12707
s#http://127.0.0.1:31337/lib/bfd57c67.components.js:4:20964
g#http://127.0.0.1:31337/lib/bfd57c67.components.js:5:12573
http://127.0.0.1:31337/lib/bfd57c67.components.js:5:16265
http://127.0.0.1:31337/lib/bfd57c67.components.js:5:22205
c#http://127.0.0.1:31337/lib/bfd57c67.components.js:6:4206
c#http://127.0.0.1:31337/lib/bfd57c67.components.js:6:4206
http://127.0.0.1:31337/lib/bfd57c67.components.js:6:4884
$digest#http://127.0.0.1:31337/lib/bfd57c67.components.js:6:7801
$apply#http://127.0.0.1:31337/lib/bfd57c67.components.js:6:9410
http://127.0.0.1:31337/lib/bfd57c67.components.js:4:26430
a#http://127.0.0.1:31337/lib/bfd57c67.components.js:4:26340
Z#http://127.0.0.1:31337/lib/bfd57c67.components.js:4:26051
http://127.0.0.1:31337/lib/bfd57c67.components.js:7:28112
d#http://127.0.0.1:31337/lib/bfd57c67.components.js:1:18351
fireWith#http://127.0.0.1:31337/lib/bfd57c67.components.js:1:19152
ready#http://127.0.0.1:31337/lib/bfd57c67.components.js:1:13970
wt#http://127.0.0.1:31337/lib/bfd57c67.components.js:1:11347
Error: Attempted to assign to readonly property.
r#http://127.0.0.1:31337/lib/bfd57c67.components.js:22:3139
r#http://127.0.0.1:31337/lib/bfd57c67.components.js:5:3551
http://127.0.0.1:31337/lib/bfd57c67.components.js:5:19730
http://127.0.0.1:31337/lib/bfd57c67.components.js:5:12707
s#http://127.0.0.1:31337/lib/bfd57c67.components.js:4:20964
g#http://127.0.0.1:31337/lib/bfd57c67.components.js:5:12573
http://127.0.0.1:31337/lib/bfd57c67.components.js:5:16265
http://127.0.0.1:31337/lib/bfd57c67.components.js:5:22205
c#http://127.0.0.1:31337/lib/bfd57c67.components.js:6:4206
c#http://127.0.0.1:31337/lib/bfd57c67.components.js:6:4206
http://127.0.0.1:31337/lib/bfd57c67.components.js:6:4884
$digest#http://127.0.0.1:31337/lib/bfd57c67.components.js:6:7801
$apply#http://127.0.0.1:31337/lib/bfd57c67.components.js:6:9410
http://127.0.0.1:31337/lib/bfd57c67.components.js:4:26430
a#http://127.0.0.1:31337/lib/bfd57c67.components.js:4:26340
Z#http://127.0.0.1:31337/lib/bfd57c67.components.js:4:26051
http://127.0.0.1:31337/lib/bfd57c67.components.js:7:28112
d#http://127.0.0.1:31337/lib/bfd57c67.components.js:1:18351
fireWith#http://127.0.0.1:31337/lib/bfd57c67.components.js:1:19152
ready#http://127.0.0.1:31337/lib/bfd57c67.components.js:1:13970
wt#http://127.0.0.1:31337/lib/bfd57c67.components.js:1:11347
Update 1
Upon some debugging, it turns out that error gets thrown from angularjs-bootstrap-datetimepicker package when it tries to set $render to a function,
var ngModelController = $element.controller('ngModel')
var configuration = createConfiguration()
$scope.screenReader = configuration.screenReader
// Behavior
$scope.changeView = changeView
ngModelController.$render = $render --> in this line
I have an RSpec feature spec that tests the login for my app. It passes when I run it in RSpec with Capybara, but when I try to run it flagged with js: true using Capybara-webkit, it fails. This is a problem because my entire app is behind the login, and if I can't get this bit to run I don't know how to do feature specs for the rest of the app.
Here's what I have tried:
Installing all the Capybara-webkit dependencies listed here. I'm running my app in a Docker container built on the ruby:2.3 image, which is built on Jessie.
Setting up DatabaseCleaner per this blog post. My database_cleaner.rb file is below.
Using the Headless gem (headless.rb below)
Running RSpec like so: xvfb-run -a bin/rspec spec/features/log_in_spec.rb (seems no different than running it normally with Headless)
How do I get my login specs to work under Capybara-webkit? Some of my specs will need to be flagged for JS and some won't, but they'll all need the user to be logged in. Thank you.
log_in_spec.rb
require 'rails_helper'
RSpec.feature "Log in", type: :feature do
scenario "as admin" do
user = create(:admin)
# Tried this instead of with Capybara, works with Capybara but not capybara-webkit
# login_as user, scope: :user, run_callbacks: false
visit root_path
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
find('.btn-primary').click
expect(page).to have_content('Admin')
end
end
spec_helper.rb
require 'capybara/rspec'
require 'paperclip/matchers'
RSpec.configure do |config|
Capybara.javascript_driver = :webkit
Capybara.app_host = 'https://192.168.99.101'
config.include Paperclip::Shoulda::Matchers
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
mocks.verify_doubled_constant_names = true
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.disable_monkey_patching!
if config.files_to_run.one?
config.default_formatter = 'doc'
end
end
rails_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
require 'capybara/rails'
require 'devise'
require 'support/controller_macros'
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.use_transactional_fixtures = false
config.filter_rails_from_backtrace!
config.include Warden::Test::Helpers
config.before :suite do
Warden.test_mode!
end
config.after :each do
Warden.test_reset!
end
end
# Added headless gem and this code thanks to this post: http://stackoverflow.com/a/28706535/3043668
if ENV['HEADLESS']
require 'headless'
headless = Headless.new
headless.start
at_exit { headless.stop }
end
spec/support/database_cleaner.rb
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, js: true) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
spec/support/headless.rb
RSpec.configure do |config|
config.around type: :feature do |example|
Headless.ly do
example.run
end
end
end
spec/support/capybara.rb
Capybara::Webkit.configure do |config|
config.debug = true
config.allow_unknown_urls
config.timeout = 5
config.ignore_ssl_errors
config.skip_image_loading
end
Here is a gist of the debug output from Capybara-webkit when I run the test. It looks like it's trying the same thing over and over.
UPDATE
I removed my Capybara.app_host setting, and the non-JS test still passes, but when I run it under capybara-webkit, I see this in the debig output:
Received 0 from "https://127.0.0.1:37193/login"
Page finished with false
Load finished
Page load from command finished
Wrote response false "{"class":"InvalidResponseError","message":"Unable to load URL: http://127.0.0.1:37193/login because of error loading https://127.0.0.1:37193/login: Unknown error"}"
Received "Reset()"
Started "Reset()"
undefined|1|SecurityError: DOM Exception 18: An attempt was made to break through the security policy of the user agent.
It's trying to visit("/login") and it is being redirected to the https version, and this is making it fail. How do I make it succeed?
The first reason is that the record after save procedure c=keep not the password in plain view, but seems that it is good in this case:
user = create(:admin)
# ...
user = User.first # wrong way
#...
fill_in 'Password', with: 'password'
The second reason in fail to login is that factory girl and capybara uses separate connections, so and data created in one session isn't available in another. To fix it use single connection patch (put it to spec/support) as described here.
This was a hard one. But the issue was that I had set force_ssl = true in my application.rb, stupidly, instead of putting it in production.rb and development.rb like a normal person.
I also had set Capybara-webkit's app_host, which, as it turned out, I did not need to do. After removing that, and running capybara-webkit with debug on, I saw that it was trying to redirect from http://localhost:45362/login (or whatever port) to https://localhost:45362/login (note the https!) and that this was causing a DOM 18 security error or whatever, and this was making it choke. I turned off force_ssl and now it works like a champ. Hope this helps you not tear your hair out.
I have a rails project using rspec 3.4.0 capybara 2.6.2 and capybara-webkit 1.8.0.
I have a simple feature test which is as follows:
require 'rails_helper'
RSpec.feature "Seller Features", type: :feature do
let!(:sub_category) { FactoryGirl.create(:sub_category) }
#all tests will create a user - sign them in and land them on the homepage
background do
sign_in_as
end
scenario "Buyer creates a seller profile", :js => true do
click_link("SELL ON SITE",match: :first)
expect(page).to have_text("Reach thousands of customers in your area")
click_link("Create an Activity",match: :first)
expect(current_path).to eql (new_seller_profile_path)
fill_in "seller_profile[business_name]", :with => "Test company"
fill_in "seller_profile[business_email]", :with => "test#email.com"
fill_in "seller_profile[business_phone_number]", :with => "07771330510"
fill_in "seller_profile[business_description]", :with => "This is a test company"
find('label[for="social"]').click
find("#facebook-placeholder").click
fill_in "seller_profile[business_facebook_url]", :with => "https://www.facebook.com/test"
click_button("CREATE AN ACTIVITY")
fill_in "seller_profile[requested_postcode]", :with => "EH21 8PB"
click_button("Submit")
click_link("Continue")
expect(page).to have_text("Choose the type of activity that you want to create")
end
end
The test passes successfully. The problem is it takes this length of time to run:
Finished in 4 minutes 26.2 seconds (files took 7.19 seconds to load)
This seems ridiculously long! During the execution my cpu is almost idle so I am not sure what is causing the length of execution time? Is this a reasonable normal amount of time for such a simple feature test?! Please help!
I don't know if this will help but this is my spec_helper.rb file:
ENV["RAILS_ENV"] ||= "test"
ENV['SERVER_NAME'] = "user.myapp.com"
require File.expand_path("../../config/environment", __FILE__)
require "rspec/rails"
Capybara::Webkit.configure do |config|
# Enable debug mode. Prints a log of everything the driver is doing.
config.debug = false
config.allow_unknown_urls
# Allow pages to make requests to any URL without issuing a warning.
# Allow a specifc domain without issuing a warning.
config.allow_url("https://checkout.stripe.com")
config.allow_url("https://checkout.stripe.com/v3/data/languages/en.json")
# Timeout if requests take longer than 5 seconds
config.timeout = 60
# Don't raise errors when SSL certificates can't be validated
config.ignore_ssl_errors
end
Capybara.javascript_driver = :webkit
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do |example|
DatabaseCleaner.strategy= example.metadata[:js] ? :truncation : :transaction
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
config.include SignInHelpers, type: :feature
config.mock_with :rspec
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
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
end
It was waiting for 3rd party javascripts - debug mode turned on was the key to finding out what was hanging up capybara webkit. Thanks Tom Walpole.
I been using :firefox drivers for capyabara and this test was passing but when I switch to poltergeist driver the test been failing now with the following error:
Minitest::UnexpectedError: Capybara::ElementNotFound: Unable to find field "email"
Here is the capybara and poltergeist setup:
def setup
# FactoryGirl.lint
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.start
Capybara.run_server = true
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, :js_errors => false)
end
Capybara.default_driver = :poltergeist
Capybara.current_driver = :poltergeist
Capybara.javascript_driver = :poltergeist
Capybara.app_host = 'http://localhost:4200'
Capybara.server_port = 3000
Capybara.default_max_wait_time = 5
end
Here is the test:
test "User should be able to signin" do
visit '/'
wait_for_ajax
fill_in 'email', with: #user.email
fill_in 'password', with: #user.password
assert true
end
So, when I changed the driver to :selenium the test pass with no error.
How do I setup/fix poltergeist to pass this test?
I took screenshot and it shows loading indicator which is a div that is removed in afterModel Ember hook using the following code:
_ember['default'].$('.ember-load-indicator').remove();
For Ajax calls we have the following function as test helper to wait for ajax calls:
def wait_for_ajax
Timeout.timeout(Capybara.default_wait_time) do
loop until finished_all_ajax_requests?
end
end
def finished_all_ajax_requests?
page.evaluate_script('jQuery.active').zero?
end
I suspect it's a timing issue... When using poltergeist vs a browser, you can get these weird behaviours, where an element is present, but not really loaded hence the error... An easy way to confirm this is by putting a sleep prior to fill_in email... put sleep 10 just to be safe...
Additional tip:
To help debug headless tests, consider adding screenshots on failures -
Add this to the end of your Capybara setup:
Capybara::Screenshot.register_filename_prefix_formatter(:rspec) do |example|
"screenshot_#{example.description.gsub(' ', '-').gsub(/^.*\/spec\//,'')}"
end
screenshot_path = "#{PROJECT_ROOT}/screenshot/"
Capybara.save_and_open_page_path = screenshot_path
It's definitely best to divide specs up so you have specs pertaining to each aspect of the MVC architecture, but I think there is a slight crossover with controller specs and view specs.
With view specs, you should only be concerned with the view, but with controller specs I still think it would be a good idea to test that the correct view is rendered, and maybe even test the content of the view, although more in-depth testing of the content should take place in the view spec.
Despite this clear article, https://www.relishapp.com/rspec/rspec-rails/v/2-1/docs/controller-specs/render-views, describing how to do this, I just cannot integrate my view and controller specs.
I keep getting the error undefined method 'contain'!
Here's my spec_helper:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'
require 'capybara/rails'
require 'factory_girl_rails'
require 'ap'
def set(factory)
#user = FactoryGirl.create(factory)
end
def sign_up(first_name, last_name, profile_name, email, password)
visit "/"
click_link "Register"
fill_in('First name', with: first_name)
fill_in('Last name', with: last_name)
fill_in('Profile name', with: profile_name)
fill_in('Email', with: email)
fill_in('Password', with: password)
fill_in('Password confirmation', with: password)
click_button 'Sign up'
end
def sign_in(email, password)
visit "/"
click_link "Sign In"
fill_in('Email', with: email)
fill_in('Password', with: password)
click_button 'Sign in'
end
def sign_out
visit "/"
click_link "Sign Out"
end
#Webrat.configure do |config|
# config.mode = :rails
#end
#webrat
require 'capybara/poltergeist'
# Capybara.javascript_driver = :poltergeist
Capybara.javascript_driver = :selenium
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
RSpec.configure do |config|
# true means 'yes, filter these specs'
config.filter_run_excluding stress: true
# config.current_driver = :webkit
# config.use_transactional_fixtures = false
# config.include Capybara::DSL
DatabaseCleaner.strategy = :truncation
config.after(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
# config.before(:suite) do
# DatabaseCleaner.strategy = :transaction
# DatabaseCleaner.clean_with(:truncation)
# DatabaseCleaner.start
# end
# config.after(:each) do
# DatabaseCleaner.clean
# end
#config.after(:suite) do
# DatabaseCleaner.strategy = :transaction
# DatabaseCleaner.clean_with(:truncation)
# DatabaseCleaner.clean
# end
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
# config.fixture_path = "#{::Rails.root}/spec/fixtures"
# config.include RSpec::Rails::RequestExampleGroup, type: :feature
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
I18n.enforce_available_locales = true
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = "random"
end
Here's my controller spec:
require "spec_helper"
describe UserFriendshipsController, type: :controller do
render_views
let (:user_1) { FactoryGirl.create(:user_1)}
before {
sign_in user_1
get :index
}
it "renders the :index view" do
response.should render_template(:index)
end
it "view contains expected html" do
# a sanity test more than anything
response.should contain("Welcome to the home page")
end
end
Upon running this spec I get this:
.F
Failures:
1) UserFriendshipsController view contains expected html
Failure/Error: response.should contain("Listing widgets")
NoMethodError:
undefined method `contain' for #<RSpec::Core::ExampleGroup::Nested_1:0x00000008632268>
# ./spec/controllers/user_friendships_spec.rb:18:in `block (2 levels) in <top (required)>'
Finished in 0.1835 seconds
2 examples, 1 failure
Why is this happening? How can I get this to work?
If you look at the relish documentation for the current 2.14 version of Rspec you'll see that they're using match now instead:
expect(response.body).to match /Listing widgets/m
Using the should syntax, this should work:
response.body.should match(/Welcome to the home page/)
Right, it was a very unclear article from Rspec that caused this error. It was using webrat in its example and didn't think to tell you. If anyone else gets here, you can add webrat to your gemfile to use the contain method:
Gemfile
group :test do
gem 'webrat'
end
However, it makes a lot more sense to use rspec's native match method:
expect(response.body).to match /Listing widgets/m