Byebug does not pauses in controller in RSpec request spec - ruby-on-rails-3

I have added byebug breakpoint in spec code and it pauses the code there.
require 'rails_helper'
RSpec.describe "UsedCars", :type => :request do
describe "POST /used_cars" do
it "creates a used car ad" do
byebug # <- stop here
count = UsedCar.count
post used_cars_path, used_car: attributes_for(:used_car)
expect(UsedCar.count).to eq(count + 1)
end
end
end
But when I add the breakpoint in the controller-action method of the request being tested. it does not stop there. I have even tried it in the top-level before_filter for application_controller.
app/controllers/used_car_controller.rb
def create
byebug # <- does not stop here
....
end
Even in the application_controller.rb
# top before_filter
before_fitler :stop
...
def stop
byebug # does not even stop here
end
I am using Rails 3 with ruby 2.2.8

Related

devise and rspec-rails - How to sign-in user in Request type specs (specs tagged with type: :request)?

Environment
Rails 4.2.0
ruby-2.2.1 [ x86_64 ]
devise 3.4.1
rspec-core 3.2.2
rspec-rails 3.2.1
In my /spec/rails_helper.rb I have included Devise helpers for spec files tagged with type: :controller and type: :request
spec/rails_helper.rb
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# 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 = false
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.before(:suite) do
begin
DatabaseCleaner.start
FactoryGirl.lint
ensure
DatabaseCleaner.clean
end
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run # ==================> L-60
end
end
config.include FactoryGirl::Syntax::Methods
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
config.include Devise::TestHelpers, type: :controller
config.include Devise::TestHelpers, type: :request
end
With that config in place the type: controller specs runs fine. However when running type: request specs I am getting following error:
Failure/Error: Unable to find matching line from backtrace
NoMethodError:
undefined method `env' for nil:NilClass
# /home/.rvm/gems/ruby-2.2.1#myapp/gems/devise-3.4.1/lib/devise/test_helpers.rb:24:in `setup_controller_for_warden'
# ./spec/rails_helper.rb:60:in `block (3 levels) in <top (required)>'
# /home/.rvm/gems/ruby-2.2.1#simplyhomeapp/gems/database_cleaner-1.4.1/lib/database_cleaner/generic/base.rb:15:in `cleaning'
# /home/.rvm/gems/ruby-2.2.1#simplyhomeapp/gems/database_cleaner-1.4.1/lib/database_cleaner/base.rb:92:in `cleaning'
# /home/.rvm/gems/ruby-2.2.1#simplyhomeapp/gems/database_cleaner-1.4.1/lib/database_cleaner/configuration.rb:86:in `block (2 levels) in cleaning'
# /home/.rvm/gems/ruby-2.2.1#simplyhomeapp/gems/database_cleaner-1.4.1/lib/database_cleaner/configuration.rb:87:in `call'
# /home/.rvm/gems/ruby-2.2.1#simplyhomeapp/gems/database_cleaner-1.4.1/lib/database_cleaner/configuration.rb:87:in `cleaning'
# ./spec/rails_helper.rb:59:in `block (2 levels) in <top (required)>'
https://github.com/plataformatec/devise/blob/master/lib/devise/test_helpers.rb#L24 is following
def setup_controller_for_warden #:nodoc:
#request.env['action_controller.instance'] = #controller # ==================> L-24
end
I am aware that #request instance is not available for :request type specs and hence the error.
Are there any helpers available we can use to sign-in a user in :request type specs when using Devise?
I found a similar issue https://github.com/plataformatec/devise/issues/1114, the reply to which suggests following:
If you're doing integration tests, make sure to sign in your user in the tradicional way, by filling the sign in form and submitting.
But I would like to by pass the actual login for specs which requires a signed-in user.
Thanks.
With the help of a few SO posts(please refer to the References section below) I have managed to achieve the desired solution. I am posting my working code below, in case it can help others looking out for the same:
spec/rails_helper.rb
RSpec.configure do |config|
....
....
config.include Devise::TestHelpers, type: :controller
config.include Warden::Test::Helpers, type: :request
end
spec/shared_contexts.rb
RSpec.shared_context "api request global before and after hooks" do
before(:each) do
Warden.test_mode!
end
after(:each) do
Warden.test_reset!
end
end
RSpec.shared_context "api request authentication helper methods" do
def sign_in(user)
login_as(user, scope: :user)
end
def sign_out
logout(:user)
end
end
/spec/requests/api/logout_spec.rb
require 'rails_helper'
require 'shared_contexts'
RSpec.describe "Api Logout", :type => :request do
include_context "api request authentication helper methods"
include_context "api request global before and after hooks"
let(:email) { 'test_user1#example.com' }
let(:password) { 'password' }
# Assumes you have FactoryGirl included in your application's test group.
let!(:user) { create(:user, email: email, password: password) }
context "DELETE /logout" do
it "responds with 204 and signs out the signed-in user" do
sign_in(user)
# Till not figured out how to assert Warden has successfully logged in the user like we can do in a Devise controller spec by asserting subject.current_user. If anybody knows a way to do it please share.
# expect(subject.current_user).to_not be_nil
delete "/logout"
expect(response).to have_http_status(204)
end
end
end
I have still not figured out how to assert Warden has successfully logged in the user like we can do in a Devise controller spec by asserting expect(subject.current_user).to_not be_nil. If anybody knows a way to do it please share.
References
Integration test with rspec and devise sign_in env
https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara
https://github.com/hassox/warden/blob/master/lib/warden/test/helpers.rb
undefined method 'env' for nil:NilClass
https://github.com/plataformatec/devise/wiki/How-To:-Stub-authentication-in-controller-specs
The code in the above link still relies on a request object which is only available in Controller specs. Thus not useful for type: :request specs.
https://github.com/plataformatec/devise/issues/3555
Thanks,
Jiggnesh
While the popular answer here, also replicated on the Devise wiki, is ok, it is simplest to just:
spec/rails_helper.rb
RSpec.configure do |config|
# ...
config.include Devise::Test::IntegrationHelpers, type: :request
end
And just use sign_in in your request spec. This is the equivalent of declaring include Devise::Test::IntegrationHelpers in an system/feature spec or Rails system/controller test.
Reference
Devise wiki: How to sign in and out a user in request type specs - Simple approach

Rspec, guard, spork and capybara/selenium - configuration for js tests

I'm using this solution to avoid issues with the database during javascript tests.
The first run through the suite, the tests run fine, all passing.
If I run the entire suite again, they'll still pass.
But, if I run an individual spec file and then try to run the suite (or other individual test), I get this error:
An error occurred in an after hook
ActiveRecord::StatementInvalid: ArgumentError: prepare called on a closed database: rollback transaction
occurred at /home/steveq/.rvm/gems/ruby-1.9.3-p194#rails32/gems/sqlite3-1.3.7/lib/sqlite3/database.rb:91:in `initialize'
1) Signing up with valid information
Failure/Error: visit "/sign_up"
ActiveRecord::StatementInvalid:
ArgumentError: prepare called on a closed database: PRAGMA table_info("users")
# ./app/controllers/registrations_controller.rb:3:in `new'
# ./app/controllers/registrations_controller.rb:3:in `new'
# ./spec/features/sign_up_feature_spec.rb:5:in `block (2 levels) in <top (required)>'
If I reload guard, the tests will pass again.
Does anyone have any insight into what's happening here or any possible solutions? I've tried every variation I can think of, and here's my spec_helper file to show the things I've tried (the variations are commented out, the current code - what's suggested on the capybara page - is what I'm using now).
require 'rubygems'
require 'spork'
#uncomment the following line to use spork with the debugger
#require 'spork/ext/ruby-debug'
Spork.prefork do
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|
#Make it so Selenium (out of thread) tests can work with transactional fixtures
#REF http://opinionated-programmer.com/2011/02/capybara-and-selenium-with-rspec-and-rails-3/#comment-220
# ActiveRecord::ConnectionAdapters::ConnectionPool.class_eval do
# def current_connection_id
# # Thread.current.object_id
# Thread.main.object_id
# end
# end
# FactoryGirl short syntax
config.include FactoryGirl::Syntax::Methods
config.use_transactional_fixtures = true
# set up for use with :js => true.
# See http://stackoverflow.com/questions/8178120/capybara-with-js-true-causes-test-to-fail for more info
# config.before :suite do
# if Capybara.current_driver == :rack_test
# DatabaseCleaner.strategy = :transaction
# else
# DatabaseCleaner.strategy = :truncation
# end
# DatabaseCleaner.start
# end
# config.after do
# DatabaseCleaner.clean
# end
# standard RSPEC config
# config.before(:suite) :truncation
# else
# :transaction
# end do
# DatabaseCleaner.strategy = if example.metadata[:js]
# :truncation
# else
# :transaction
# end
# DatabaseCleaner.clean_with(:truncation)
# end
# config.before(:each) do
# DatabaseCleaner.start
# end
# config.after(:each) do
# DatabaseCleaner.clean
# end
# config.before(:each) do
# DatabaseCleaner.strategy = if example.metadata[:js]
# :truncation
# else
# :transaction
# end
# DatabaseCleaner.start
# end
# config.after(:each) do
# DatabaseCleaner.clean
# end
# 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"
config.treat_symbols_as_metadata_keys_with_true_values = true
config.filter_run :focus => true
config.run_all_when_everything_filtered = true
config.include MailerMacros
config.include LoginMacros
config.before(:each) { reset_email }
config.include Devise::TestHelpers, :type => :controller
config.extend LoginMacros, :type => :controller
end
end
Spork.each_run do
# allows capybara JS tests to run in separate thread
class ActiveRecord::Base
mattr_accessor :shared_connection
##shared_connection = nil
def self.connection
##shared_connection || retrieve_connection
end
end
# Forces all threads to share the same connection. This works on
# Capybara because it starts the web server in a thread.
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
# This code will be run each time you run your specs.
load "#{Rails.root}/config/routes.rb"
FactoryGirl.reload
# reload all the models
Dir["#{Rails.root}/app/models/**/*.rb"].each do |model|
load model
end
end
So here's what I figured out - hopefully it will help anyone else who gets into this same trouble.
Firstly, the method I was using:
Spork.each_run do
# allows capybara JS tests to run in separate thread
class ActiveRecord::Base
mattr_accessor :shared_connection
##shared_connection = nil
def self.connection
##shared_connection || retrieve_connection
end
end
# Forces all threads to share the same connection. This works on
# Capybara because it starts the web server in a thread.
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
# This code will be run each time you run your specs.
load "#{Rails.root}/config/routes.rb"
FactoryGirl.reload
# reload all the models
Dir["#{Rails.root}/app/models/**/*.rb"].each do |model|
load model
end
end
works just fine, but not, it seems, with sqlite.
The quickest fix was simply to swap out sqlite as my test db for mysql. That solved everything.
Another solution, one that I'm really digging right now, was to drop spork completely in favor of Zeus.
You can check it out via the github link, but I'll tell you why I like it.
It has no necessary config - no spork block in the spec_helper, no spork block in the guardfile.
It also speeds up server and console initialization to under a second- not a huge deal, but very, very pleasant.
My test suite (191 examples so far) went from running in around 35 seconds to 17.5 seconds - half the time.
I urge you to check it out.

how can you test the 'catch all route' using ordinary controller tests?

Note: As per RafaeldeF.Ferreira's suggestion, this question has been heavily edited since its original form.
My JSON-based app needs to return something sensible when given a bad route. We already know that the following rescue_from ActionController::RoutingError doesn't work in Rails 3.1 and 3.2:
# file: app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
rescue_from ActionController::RoutingError, :with => :not_found
...
end
(This is well documented in https://github.com/rails/rails/issues/671.) So I implemented what José Valim describes in this blog entry (item 3), and details are provided below.
But testing it has been problematic. This controller rspec test:
# file: spec/controllers/errors_controller.rb
require 'spec_helper'
require 'status_codes'
describe ErrorsController do
it "returns not_found status" do
get :not_found
response.should be(StatusCodes::NOT_FOUND)
end
end
fails with:
ActionController::RoutingError: No route matches {:format=>"json", :controller=>"sites", :action=>"update"}
Yet this integration test calls ErrorsController#not_found and succeeds:
# file: spec/requests/errors_spec.rb
require 'spec_helper'
require 'status_codes'
describe 'errors service' do
before(:each) do
#client = FactoryGirl.create(:client)
end
it "should catch routing error and return not_found" do
get "/v1/clients/login.json?id=#{#client.handle}&password=#{#client.password}"
response.status.should be(StatusCodes::OK)
post "/v1/sites/impossiblepaththatdoesnotexist"
response.status.should be(StatusCodes::NOT_FOUND)
end
end
So: Is there a way to test the 'catch all route' using ordinary controller tests?
implementation details
If you want to see the implementation, here are the relevant code snippets
# config/routes.rb
MyApp::Application.routes.draw do
... all other routes above here.
root :to => "pages#home"
match "/404", :to => "errors#not_found"
end
# config/application.rb
module MyApp
class Application < Rails::Application
config.exceptions_app = self.routes
...
end
end
# config/environments/test.rb
MyApp::Application.configure do
...
config.consider_all_requests_local = false
...
end
# app/controllers/errors_controller.rb
class ErrorsController < ApplicationController
def not_found
render :json => {:errors => ["Resource not found"]}, :status => :not_found
end
end

factory_girl rspec test failure with before_filter

I have a newbie question here. I've been following along with the rails tutorial and I've hit a snag in my tests. When I implement the following filter...
class UsersController < ApplicationController
before_filter :authenticate, :only => [:edit, :update]
...all of my user_controller_spec.rb tests related to 'GET edit' and 'PUT update' start to fail where before they passed. Here's one that should have returned true, but returned false:
describe "GET 'edit" do
before(:each) do
#user = Factory(:user)
test_sign_in(#user)
end
it "should be successful" do
get :edit, :id => #user
response.should be_success
end
end
And this is my test_sign_in code in spec_helper.rb
def test_sign_in(user)
controller.sign_in(user)
end
The sign_in method is in SessionsHelper, which is incuded in ApplicationController:
def sign_in(user)
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
current_user = user
end
I don' know how to further investigate. My guess is that since Rspec was unable to 'GET edit' there must be a log of that request that I can look at, but the test only tells me it returned false. Where can I look next?
Update: What I found in log/test.log is that every 'Processing by UsersController#index as HTML' line is followed by a redirect as follows:
Processing by UsersController#index as HTML
[1m [35mUser Load (0.2ms) [0m SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
Redirected to http://test.host/signin
Does this mean that every test index action is followed by a redirect to signin? If this were true it would seem consistent with tests including the test_sign_in method (above) failing and other tests like this one passing:
describe "GET 'index' for non-signed-in users" do
it "should deny access" do
get :index
response.should redirect_to(signin_path)
end
end
I'm going to try to wrap my head around the test_sign_in method again.
You need to call self in the sign_in helper.
def sign_in(user)
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
self.current_user = user
end

Need help Rspec test

I'm trying to learn RSpec and writing test for CRUD actions. Here is my controller:
class ArticlesController < ApplicationController
respond_to :html, :json
before_filter :authenticate_user!
# GET /articles
# GET /articles.json
def index
#articles = current_user.articles.all
respond_with(#articles)
end
# GET /articles/1
# GET /articles/1.json
def show
#article = current_user.articles.find(params[:id])
respond_with #article
end
# GET /articles/new
# GET /articles/new.json
def new
#article = current_user.articles.build
respond_with #article
end
# GET /articles/1/edit
def edit
#article = get_article(params[:id])
end
# POST /articles
# POST /articles.json
def create
#article = current_user.articles.build(params[:article])
flash[:notice] = "Article was successfully created!" if #article.save
respond_with(#article, location: articles_path)
end
# PUT /articles/1
# PUT /articles/1.json
def update
#article = get_article(params[:id])
if #article.update_attributes(params[:article])
flash[:notice] = "Article was successfully updated."
end
respond_with #article
end
# DELETE /articles/1
# DELETE /articles/1.json
def destroy
#article = get_article(params[:id])
#article.destroy
respond_with #article
end
private
def get_article(article_id)
current_user.articles.find(article_id)
end
end
And my articles rspec:
describe ArticlesController do
def valid_attributes
{
:title => "Introducting Node.js",
:content => "Node.js is an event-driven...."
}
end
let(:article) do
build(:article, valid_attributes)
end
describe "PUT 'update'" do
before(:each) do
controller.stub_chain(:current_user, :articles, :build) { article }
end
context "success" do
before(:each) do
article.should_receive(:update_attributes).and_return(true)
put :update, id: article.id
end
it "sets notice" do
flash[:notice].should eq("Article was successfully updated!")
end
end
end
describe "POST 'create'" do
before(:each) do
controller.stub_chain(:current_user, :articles, :build) { article }
end
context "success" do
before(:each) do
article.should_receive(:save).and_return(true)
post :create
end
it "sets notice" do
flash[:notice].should eq("Article was successfully created!")
end
it "should redirect to article path" do
response.should redirect_to(articles_path)
end
end
context "failure" do
before(:each) do
article.should_receive(:save).and_return(false).as_null_object
post :create
end
it "assigns #article" do
assigns(:article).should == article
end
end
end
end
My question is when I run rspec on PUT UPDATE test is failed. But POST test is passed. I don't have any idea what is going on. I'm using Rails 3.1.1 with omniauth. I'm not using Devise. Here is the test result. Why? Please help me guys?
Failures:
1) ArticlesController PUT 'update' success sets notice
Failure/Error: put :update, id: article.id
NoMethodError:
undefined method `find' for #<Object:0xa3cfd20>
# ./app/controllers/articles_controller.rb:61:in `get_article'
# ./app/controllers/articles_controller.rb:44:in `update'
# ./spec/controllers/articles_controller_spec.rb:46:in `block (4 levels) in <top (required)>'
Finished in 24.09 seconds
5 examples, 1 failure
Here's the thing.
When you're stubbing, you're just saying "if this method chain is called, return this." There are two issues with that. 1) the code doesn't ever call build, and 2) there's no actual associations.
I believe you'd need to stub current_user.articles to return an article collection. The problem is that AR associations aren't actual arrays, they're proxies.
See this SO post and this SO post for more details. A regular array won't treat the find method like the AR method it really is, and you're not returning a single article.
Since you have the article ID, you could just return that particular article, but your goal is to return that article from within the user's articles to avoid updating someone else's (I assume).
This SO post may also help, and this.
In other words, you may want a real user there, with real associated objects, so things like find will work w/o hackery.
(I fully recognize this isn't a real answer; I've never done this via stubbing, I've used factories/etc.)