I'm running Rails 4, trying to set up some integration test with Rspec and Capybara. I want to set up guard to run 'zeus test .' whenever I make changes. Problem is, whenever anything form the Capybara DSL is called, or whenever I try to use route helpers, I'm given errors like this:
undefined local variable or method `root_path' for #<RSpec::Core::ExampleGroup::Nested_2::Nested_1:0x007f55682c6d60>
If I replace root_path with '/' it get:
undefined method `visit' for #<RSpec::Core::ExampleGroup::Nested_2::Nested_1:0x007f556833bbb0>
If I just run 'rspec spec .' or 'zeus test .' it works fine.
I've tried removing the 'cmd: 'zeus test .' option from my Guardfile, but I'm having the same issues. It seems clear that the problem is with Guard and unrelated to zeus.
In my Gemfile:
group :development, :test do
gem 'capybara'
gem 'rspec-rails'
gem 'factory_girl_rails'
gem 'guard-rspec', require: false
gem 'better_errors'
gem 'binding_of_caller'
end
Spec helper:
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'factory_girl_rails'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
end
Spec I'm trying to run:
require 'spec_helper'
describe "HomePage" do
describe "Root page" do
before { visit root_path }
it "works!" do
page.status_code.should be(200)
end
it 'contains bottom nav buttons' do
page.should have_link 'How it works'
page.should have_link 'Customer Service'
page.should have_link 'Terms of Service'
page.should have_link 'Contact Us'
end
end
end
try add
config.include Capybara::DSL
to your spec_helper.rb
Try to add url_helpers to spec_helper.rb
RSpec.configure do |config|
...
config.include Rails.application.routes.url_helpers
end
and check my other answer about visit method missing
I fixed this problem by commenting out this line in my spec_helper.rb:
require 'rspec/autorun'
Again, the problem was only with Guard and I suppose that autorun somehow skips over the config block in the spec_helper, so everything works fine now. Hope this helps someone else having the same problem.
Related
I'm getting this strange error when I try to run my test in rails:
postgresql_adapter.rb:592:in `async_exec': PG::UndefinedTable: ERROR: relation "users" does not exist (ActiveRecord::StatementInvalid)
I don't know if this helps but my spec_helper.rb file looks like this:
require 'rubygems'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'factory_girl_rails'
require 'database_cleaner'
require 'capybara/rails'
require 'capybara/rspec'
require 'capybara/poltergeist'
require 'support/mailer_macros'
require 'support/test_helper'
require 'support/factory_girl_helper'
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new app, window_size: [1600, 1200], js_errors: false
end
RSpec.configure do |config|
config.use_transactional_fixtures = false
config.include(FactoryGirlHelper)
config.include(MailerMacros)
config.include(TestHelper)
config.before(:each) { reset_email }
config.expect_with :rspec do |c|
c.syntax = [:should, :expect]
end
Capybara.javascript_driver = :poltergeist
config.include Capybara::DSL
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation) # moving to before :each doesn't help
DatabaseCleaner.strategy = :truncation # moving to before :each doesn't help
end
config.around :each do |example| # refactoring as before/after with .start/.clean doesn't help
DatabaseCleaner.cleaning { example.run }
end
end
Anyone has any idea why this is happening? The application in the browser seems to be working fine.
Sounds like the schema for you test db is out of sync, you either need to run migrations on it or just reset/recreate it.
Ok I figured it out following the answer here: FactoryGirl screws up rake db:migrate process
So the problem was coming from factorygirl. I updated my Gemfile to look like this:
gem "factory_girl_rails", :require => false
And then also add this:
require 'factory_girl_rails'
to my spec_helper.rb file and that fixed all the issues both localy and on circleci :)
I have a very simple app I'm trying to test with rspec. I'm having a hard time figuring out if my configuration is the problem, or if it's the code. The first line of /people/index.html.erb is <h1>Totally Awesome Page</h1>.
The error:
expected to find text "Totally Awesome Page" in "Index"
./spec/features/people_spec.rb:19:in `block (3 levels) in <class:PeopleSpec>'
test gems:
group :development, :test do
gem 'rspec'
gem 'rspec-rails'
gem 'capybara'
gem 'factory_girl_rails'
end
spec/features/people_spec.rb:
require 'spec_helper'
class PeopleSpec < ActionDispatch::IntegrationTest
describe "People" do
describe "Index" do
before { visit '/people'}
it { should have_content('Totally Awesome Page')}
end
end
end
spec/spec_helper:
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'minitest/autorun'
require 'capybara/rails'
require 'capybara/rspec'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
config.include Capybara::DSL
end
routes:
people_path GET /people(.:format) people#index
POST /people(.:format) people#create
new_person_path GET /people/new(.:format) people#new
edit_person_pathGET /people/:id/edit(.:format) people#edit
person_path GET /people/:id(.:format) people#show
PATCH /people/:id(.:format) people#update
PUT /people/:id(.:format) people#update
DELETE /people/:id(.:format) people#destroy
Add gem 'launchy' and then you can use save_and_open_page after visit to see how rendered page looks like.
Add subject { page } to the spec to fix it.
If you say it than it have to point to something. In your test it doesn't.
You can use should on page to do that (page is not the only one you can test. There are more, like response or even lambdas) that way:
it "some description" do
page.should have_content('foo')
end
or if you have many tests for page than you can write them in a short way:
it { should have_content('foo') }
but you need to specify subject for it first:
subject { page }
I'm using rspec, capybara and launchy to test my web application.
Here's my spec:
require 'spec_helper'
describe "Routes" do
describe "GET requests" do
it "GET /root_path" do
visit root_path
page.should have_content("All of our statuses")
click_link "Post a New Status"
page.should have_content("New status")
fill_in "status_name", with: "Jimmy balooney"
fill_in "status_content", with: "Oh my god I am going insaaaaaaaaane!!!"
click_button "Create Status"
page.should have_content("Status was successfully created.")
click_link "Statuses"
page.should have_content("All of our statuses")
page.should have_content("Jimmy balooney")
page.should have_content("Oh my god I am going insaaaaaaaaane!!! ")
save_and_open_page
end
end
end
My .rspec
--color
--order default
and my spec_helper.rb:
# 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 'rspec/autorun'
require 'capybara/rspec'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
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|
# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.start
DatabaseCleaner.clean
end
config.after(:each) do
DatabaseCleaner.clean
end
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# 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
# 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
If you look back at my spec, you'll see a rspec spec that uses capybara to browse my application, and finishes by calling the launchy gem's save_and_open_page method to open this final page in a browser for a human to look at. At this final page, however, there is no javascript or css displayed, just pure HTML.
Does anyone have any ideas why this would be? I want to test javascript, and would prefer it if all assets were loaded.
Inside config.before(:suite) do
add:
%x[bundle exec rake assets:precompile]
to precompile your Rails assets then in your test.rb environment file add:
config.action_controller.asset_host = "file://#{::Rails.root}/public"
config.assets.prefix = 'assets_test'
to point to the location of the precompiled assets. Now you can use assets when you run Capybara. Note: make sure if you are using git to ignore that new folder.
You can just add to test.rb:
config.assets.compile = true
I can't get capybara working with rspec. It gives me this error:
undefined method `visit' for #<RSpec::Core::ExampleGroup::Nested_1:0x16529f8 #example=nil>
I know there are lots of posts about this but non of the solutions are working for me. Most of them involve the specs not being in /spec/features - which mine is in.
First the error:
$bundle exec rspec spec
F
Failures:
1) security signs users in
Failure/Error: visit "/sessions/new"
NoMethodError:
undefined method `visit' for #<RSpec::Core::ExampleGroup::Nested_1:0x16529f8 #example=nil>
# ./spec/features/security_spec.rb:4:in `(root)'
Finished in 0.006 seconds
1 example, 1 failure
Failed examples:
rspec ./spec/features/security_spec.rb:3 # security signs users in
I think its important to note that at first I was using the URL Helper 'new_sessions_path' and it kept giving me an error undefined local variable or method 'new_sessions_path'. I know it is valid because:
$ rake routes
logout_sessions GET /sessions/logout(.:format) sessions#logout
sessions POST /sessions(.:format) sessions#create
new_sessions GET /sessions/new(.:format) sessions#new
contracts POST /contracts(.:format) contracts#create
new_contracts GET /contracts/new(.:format) contracts#new
edit_contracts GET /contracts/edit(.:format) contracts#edit
GET /contracts(.:format) contracts#show
PUT /contracts(.:format) contracts#update
DELETE /contracts(.:format) contracts#destroy
root / contracts#index
My Gemfile:
source 'https://rubygems.org'
gem 'rails', '3.2.11'
gem 'execjs'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem 'activerecord-oracle_enhanced-adapter', '~> 1.4.1'
gem 'jruby-openssl'
gem 'therubyrhino'
gem 'kaminari'
gem 'nokogiri'
group :development do
gem 'warbler'
end
group :test do
gem 'rspec-rails'
gem 'capybara'
gem 'activerecord-jdbcsqlite3-adapter'
end
spec_helper.rb inside of my_app/spec:
# 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 'rspec/autorun'
# Capybara integration
require 'capybara/rspec'
require 'capybara/rails'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
# config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
# Include path helpers
config.include Rails.application.routes.url_helpers
end
my_app/spec/features/security_spec.rb:
describe "security", :type => :feature do
it "signs users in" do
visit "/sessions/new"
fill_in "username", :with => "user"
fill_in "password", :with => "pass"
click_button "Sign In"
page.should have_content('Login Successful')
end
end
I've tried defining the test above both with and without :type => :feature. It makes no difference either way. Any ideas what I should try next?
Try to add:
config.include Capybara::DSL
to your config block.
# 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 'rspec/autorun'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
# config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
# Include path helpers
config.include Rails.application.routes.url_helpers
config.include Capybara::DSL
end
Adding require 'rails_helper' at the top of my feature ended up fixing my problem:
require 'rails_helper'
describe "security", :type => :feature do
it "signs users in" do
visit new_sessions_path
fill_in "username", :with => "user"
fill_in "password", :with => "pass"
click_button "Sign In"
page.should have_content('Login Successful')
end
end
This seems odd to me since every example I've seen for rspec and capybara didn't have that require, but oh well. Problem solved.
Original Answer (older versions of rspec)
require 'spec_helper' is used by older versions of RSpec. The better answer would be require 'rails_helper'.
Since Capybara 2.0 one has to use folder spec/features Capybara commands don't work in folder spec/requests anymore.
Try performing all your setup in a before block:
spec/features/security_spec.rb
describe "security" do
before do
visit "/sessions/new"
fill_in "username", :with => "user"
fill_in "password", :with => "pass"
click_button "Sign In"
end
it "signs users in" do
page.should have_content('Login Successful')
end
end
I also had this problem,
Adding require 'rails_helper' at the top of my feature ended up fixing my problem:
require 'rails_helper'
RSpec.describe "Products", type: :request do
describe "GET /products" do
it "display tasks" do
Product.create!(:name => "samsung")
visit products_path
page.should have_content("samsung")
#expect(response).to have_http_status(200)
end
end
end
And add the 'config.include Capybara::DSL' in rails_helper.rb
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.include Capybara::DSL
end
Other than the upgrading issue which you would run into when ugprading from an older Rails app with require 'spec_helper.rb' instead of require 'rails_helper.rb', this happens for 3 known reasons:
1. Your spec isn't of type "feature"
which means Capybara doesn't know how to run it using Javascript or a browser. You want to do one of two things: 1) Typically, you want config.infer_spec_type_from_file_location! set in your RSpec.configure and that will mean that what's in the features folder will be a feature.
if you have something non-standard, you can add type: :feature to the spec describe block to turn that spec in a feature, but typically it's easier just to put them into the /features folder and let the infer setting do its job.
2. You accidentally put the visit outside of the it block
The visit must be within the it, which is within the describe. Be sure not to put the visit directly within the describe.
3. Some other kernal panic you can't see has caused Capy to shut down the spec.
This is a nasty one to diagnose but I have seen it. It means that Capy didn't actually parse this file correctly, and so somehow isn't in the right scope when it gets to the visit block. Carefully pick apart your Capy spec to figure out where you introduced it.
I induced the kernal panic today but have a let block be called page (whoops). page appears to be a reserved word for Rspec or Capy here, and it causes the kernal panic, thus leading to the spec not to parse thus leading to the visit method not being found.
in my case, it was simply changing this:
let(:page) {Page.new()}
to
let(:content_page) {Page.new()}
Notice that the word page is not reserved by Rails, and works fine as a database name and also a model name, but the specific construction of using page here as the let variable name seemed to cause Capy to get kind of crappy.
I cannot get capybara to work. I am using capybara 2.0.0
I get this error
Failure/Error: visit "/users/sign_in"
NoMethodError:
undefined method `visit' for #<RSpec::Core::ExampleGroup::Nested_21:0x007fdda4c6eba0>
on this spec
spec/requests/forgot_password_spec.rb
describe "forgot password" do
it "redirects user to users firms subdomain" do
visit "/users/sign_in"
end
end
I do not get any errors that it cannot find capybara and it's included in the spec_helper.rb
spec_helper.rb
require 'rubygems'
require 'spork'
require 'database_cleaner'
Spork.prefork do
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'
require 'rspec/autorun'
require 'factory_girl'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
config.extend ControllerMacros, :type => :controller
config.include RequestMacros, :type => :request
config.mock_with :rspec
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
config.infer_base_class_for_anonymous_controllers = false
end
Spork.each_run do
FactoryGirl.reload
end
end
Has anybody else encountered this?
If you've got version >= 2.0, any tests that use Capybara methods like visit should go under a spec/features directory, and not under spec/requests, where they'd normally reside in Capybara 1.1.2.
Have a look at the following links for more information:
rspec-rails and capybara 2.0: what you need to know
rspec-rails gem Capybara page
If you don't want to use a spec/features directory, you should be able to mark a test as a feature in the following way and have Capybara methods work:
describe "Some action", type: :feature do
before do
visit "/users/sign_in"
# ...
end
# ...
end
In my case, I got this error because I forgot to putrequire "spec_helper"
at the top of my new spec file.
I've done it enough times that I'm adding an answer to an already answered question in hopes that it helps some other knucklehead (or most likely me searching this again in the future).