I'm following this post about setting up authentication in the routes of my Rails 4 application.
Here is my routes.rb file:
Rails.application.routes.draw do
devise_for :employees, :controllers => { registrations: 'employees/registrations' }
devise_for :clients
authenticate :employee do
resources :quotation_requests, only: [:show, :edit,:index, :update, :destroy]
end
resources :quotation_requests, only: [:new, :create]
get '/dashboard' => 'dashboard#show', as: 'show_dashboard'
root to: 'home#index'
end
Here is my quotation_requests_controller_spec.rb file:
require 'rails_helper'
RSpec.describe QuotationRequestsController, type: :controller do
describe "GET index" do
it "renders :index template" do
get :index
expect(response).to render_template(:index)
end
it "assigns quotation requests to template" do
quotation_requests = FactoryGirl.create_list(:quotation_request, 3)
get :index
expect(assigns(:quotation_requests)).to match_array(quotation_requests)
end
end
describe "GET edit" do
let(:quotation_request) { FactoryGirl.create(:quotation_request)}
it "renders :edit template" do
get :edit, id: quotation_request
expect(response).to render_template(:edit)
end
it "assigns the requested quotation request to template" do
get :edit, id: quotation_request
expect(assigns(:quotation_request)).to eq(quotation_request)
end
end
describe "PUT update" do
let(:quotation_request) { FactoryGirl.create(:quotation_request)}
context "valid data" do
new_text = Faker::Lorem.sentence(word_count=500)
let(:valid_data) { FactoryGirl.attributes_for(:quotation_request, sample_text: new_text)}
it "redirects to quotation_request#showtemplate" do
put :update, id: quotation_request, quotation_request: valid_data
expect(response).to redirect_to(quotation_request)
end
it "updates quotation request in the database" do
put :update, id: quotation_request, quotation_request: valid_data
quotation_request.reload #need to reload the object because we have just updated it in the database so need to get the new values
expect(quotation_request.sample_text).to eq(new_text)
end
end
context "invalid data" do
let(:invalid_data) { FactoryGirl.attributes_for(:quotation_request, sample_text: "", number_of_words: 400)}
it "renders the :edit template" do
put :update, id: quotation_request, quotation_request: invalid_data
expect(response).to render_template(:edit)
end
it "does not update the quotation_request in the database" do
put :update, id: quotation_request, quotation_request: invalid_data
quotation_request.reload
expect(quotation_request.number_of_words).not_to eq(400)
end
end
end
describe "GET new", new: true do
it "renders :new template" do
get :new
expect(response).to render_template(:new)
end
it "assigns new QuotationRequest to #quotation_request" do
get :new
expect(assigns(:quotation_request)).to be_a_new(QuotationRequest)
end
end
describe "GET show" do
#this test requires that there be a quotation request in the database
let(:quotation_request) { FactoryGirl.create(:quotation_request) }
context 'invalid request' do
it "does not render :show template if an employee or client is not signed in" do
#setup
quotation_request = create(:quotation_request)
#exercise
get :show, id: quotation_request
#verification
expect(response).to_not render_template(:show)
end
end
context 'valid request' do
sign_in_proofreader
it "renders :show template if an employee or client is signed in" do
#setup
quotation_request = create(:quotation_request)
#exercise
get :show, id: quotation_request
#verification
expect(response).to render_template(:show)
end
it "assigns requested quotation_request to #quotation_request" do
get :show, id: quotation_request
expect(assigns(:quotation_request)).to eq(quotation_request)
end
end
end
describe "POST create", post: true do
context "valid data" do
let(:valid_data) {FactoryGirl.nested_attributes_for(:quotation_request)}
it "redirects to quotation_requests#show" do
post :create, quotation_request: valid_data
expect(response).to redirect_to(quotation_request_path(assigns[:quotation_request]))
end
it "creates new quotation_request in database" do
expect {
post :create, quotation_request: valid_data
}.to change(QuotationRequest, :count).by(1)
end
end
context "invalid data" do
let(:invalid_data) {FactoryGirl.nested_attributes_for(:quotation_request).merge(sample_text: 'not enough sample text')}
it "renders :new template" do
post :create, quotation_request: invalid_data
expect(response).to render_template(:new)
end
it "doesn't creates new quotation_request in database" do
expect {
post :create, quotation_request: invalid_data
}.not_to change(QuotationRequest, :count)
end
end
end
describe "DELETE destroy" do
let(:quotation_request) { FactoryGirl.create(:quotation_request) }
it "redirects to the quotation request#index" do
delete :destroy, id: quotation_request
expect(response).to redirect_to(quotation_requests_path)
end
it "delets the quotation request from the database" do
delete :destroy, id: quotation_request
expect(QuotationRequest.exists?(quotation_request.id)).to be_falsy
end
end
end
My quotation_requests_controller.rb
class QuotationRequestsController < ApplicationController
# before_action :authenticate_employee!, :only => [:show]
def index
#quotation_requests = QuotationRequest.all
end
def new
#quotation_request = QuotationRequest.new
#quotation_request.build_client
end
def edit
#quotation_request = QuotationRequest.find(params[:id])
end
def create
client = Client.find_or_create(quotation_request_params[:client_attributes])
#quotation_request = QuotationRequest.new(quotation_request_params.except(:client_attributes).merge(client: client))
if #quotation_request.save
ClientMailer.quotation_request_created(client.email, #quotation_request.id).deliver_now
redirect_to #quotation_request, notice: 'Thank you.'
else
render :new
end
end
def show
#quotation_request = QuotationRequest.find(params[:id])
end
def update
#quotation_request = QuotationRequest.find(params[:id])
if #quotation_request.update(quotation_request_params)
redirect_to #quotation_request
else
render :edit
end
end
def destroy
QuotationRequest.destroy(params[:id])
redirect_to quotation_requests_path
end
private
def quotation_request_params
params.require(:quotation_request).permit(:number_of_words, :return_date, :sample_text, :client_attributes => [:first_name, :last_name, :email])
end
end
I know the routes authentication works because if I test them in the browser I get redirected to the sign_in page. However, the tests don't pass in Rspec.
if I put this code in the quotation_requests_controller.rb:
before_action :authenticate_employee!, :only => [:show]
The rspec tests pass. So for some reason Rspec does not register the authentication of the routes.
Here is the output from Rspec for the tests run with the authenticated routes:
QuotationRequestsController
GET index
valid request
renders :index template for signed in employee
assigns quotation requests to template
invalid request
does not render :index template without a signed in employee (FAILED - 1)
GET edit
valid request
renders :edit template with a signed in employee
assigns the requested quotation request to template
invalid request
does not render the :edit template without a signed in employee (FAILED - 2)
PUT update
valid request
valid data
redirects to quotation_request#showtemplate
updates quotation request in the database
invalid data
renders the :edit template
does not update the quotation_request in the database
invalid request
redirects user to the sign in page (FAILED - 3)
GET new
renders :new template
assigns new QuotationRequest to #quotation_request
GET show
invalid request
does not render :show template if an employee or client is not signed in (FAILED - 4)
valid request
renders :show template if an employee or client is signed in
assigns requested quotation_request to #quotation_request
POST create
valid data
redirects to quotation_requests#show
creates new quotation_request in database
invalid data
renders :new template
doesn't creates new quotation_request in database
DELETE destroy
valid request
redirects to the quotation request#index
delets the quotation request from the database
invalid request
does not delete the quotation request without a signed in employee (FAILED - 5)
Failures:
1) QuotationRequestsController GET index invalid request does not render :index template without a signed in employee
Failure/Error: expect(response).to_not render_template(:index)
Didn't expect to render index
# ./spec/controllers/quotation_requests_controller_spec.rb:43:in `block (4 levels) in <top (required)>'
# -e:1:in `<main>'
2) QuotationRequestsController GET edit invalid request does not render the :edit template without a signed in employee
Failure/Error: expect(response).to_not render_template(:edit)
Didn't expect to render edit
# ./spec/controllers/quotation_requests_controller_spec.rb:92:in `block (4 levels) in <top (required)>'
# -e:1:in `<main>'
3) QuotationRequestsController PUT update invalid request redirects user to the sign in page
Failure/Error: expect(response).to_not redirect_to(quotation_request)
Didn't expect to redirect to #<QuotationRequest:0x007fe7eb69c8c0>
# ./spec/controllers/quotation_requests_controller_spec.rb:182:in `block (4 levels) in <top (required)>'
# -e:1:in `<main>'
4) QuotationRequestsController GET show invalid request does not render :show template if an employee or client is not signed in
Failure/Error: expect(response).to_not render_template(:show)
Didn't expect to render show
# ./spec/controllers/quotation_requests_controller_spec.rb:217:in `block (4 levels) in <top (required)>'
# -e:1:in `<main>'
5) QuotationRequestsController DELETE destroy invalid request does not delete the quotation request without a signed in employee
Failure/Error: expect(QuotationRequest.exists?(quotation_request.id)).to be_truthy
expected: truthy value
got: false
# ./spec/controllers/quotation_requests_controller_spec.rb:361:in `block (4 levels) in <top (required)>'
# -e:1:in `<main>'
Finished in 2.11 seconds (files took 1.75 seconds to load)
23 examples, 5 failures
Failed examples:
rspec ./spec/controllers/quotation_requests_controller_spec.rb:37 # QuotationRequestsController GET index invalid request does not render :index template without a signed in employee
rspec ./spec/controllers/quotation_requests_controller_spec.rb:83 # QuotationRequestsController GET edit invalid request does not render the :edit template without a signed in employee
rspec ./spec/controllers/quotation_requests_controller_spec.rb:171 # QuotationRequestsController PUT update invalid request redirects user to the sign in page
rspec ./spec/controllers/quotation_requests_controller_spec.rb:208 # QuotationRequestsController GET show invalid request does not render :show template if an employee or client is not signed in
rspec ./spec/cont
Why do the routes I have written not work in Rspec tests?
I take it you are using rspec-rails in your rails app.
Rspec-rails sets up a lot of convenience methods for you, but it also introduces some black-magic, which can lead to some unexpected results - like this.
As you can see here it is explained in the comments for controller specs:
# Supports a simple DSL for specifying behavior of ApplicationController.
# Creates an anonymous subclass of ApplicationController and evals the
# `body` in that context. Also sets up implicit routes for this
# controller, that are separate from those defined in "config/routes.rb".
I guess the logic here is, controller features are different from routing and should be tested separately (and indeed rspec-rails offers a test group for routing), so we do not need the routes for controller specs, meaning you should be able to test your controller without setting up the routes.
In my oppinion, testing the redirect for unauthenticated users is more of an integration test, since it requires multiple parts of your application to work together and as such should not be tested in the controller context, but rather as a feature in some blackbox test.
You can write integration tests by placing them in one of these directories spec/requests, spec/api, and spec/integration or by explicitely declaring their type with
RSpec.describe "Something", type: :request do
or place it in spec/features or declare the type as
RSpec.describe "Something", type: :feature do
depending on which level you want to test the redirect (meaning: only test the request-response cycle, or run it in a simulated browser).
Please refer to the documentation for integration tests on the rspec-rails github page for more information.
Related
How to test using shoulda-matchers for these actions, to response JSON success 200, and fail 422
and how to test with normal RSpec: both cases if you can:
I think there is missing some information for shoulda matches on its repository.
if you can help thanks very much.
module V1
class MeasurementsController < ApplicationController
protect_from_forgery with: :null_session
before_action :set_measurement, only: %i[destroy]
def index
measurement = Measurement.all
render json: MeasurementSerializer.new(measurement).serialized_json
end
def create
measurement = Measurement.new(measurement_params)
if measurement.save
render json: MeasurementSerializer.new(measurement).serialized_json
else
render json: { error: measurement.errors.messages }, status: 422
end
end
def destroy
if #measurement.destroy
head :no_content
else
render json: { error: measurement.errors.messages }, status: 422
end
end
private
def set_measurement
#measurement = Measurement.find(params[:id])
end
def measurement_params
params.require(:measurement).permit(:time, :date, :sport_id)
end
end
end
end```
No need for shoulda-matchers
You can test with something like this:
require 'rails_helper'
describe V1::MeasurementsController do
describe '#index', type: request do
it 'respond with 200' do
get /your/endpoint
expect(response).to have_http_status(200)
end
end
end
what works for me
describe 'GET #index' do
before { get :index }
it { should respond_with(200) }
end
I am sending the request using postman, all the required fields are in place, however, I get the params required errors, like I send nothing when I actually do send the required params to the server.
I was reading this blog that says in order to get json reponse in devise I just need to add respond_to :json line in devise controllers, but it seems this is not enough.
I would've add more info to the question if I would know what exactly is needed.
routes:
namespace :api, defaults: { format: :json } do
devise_for :users, controllers: {
registrations: 'api/users/registrations',
sessions: 'api/users/sessions',
invitations: 'api/users/invitations'
}
end
controllers:
module Api
class Users::RegistrationsController < Devise::RegistrationsController
respond_to :json
layout false, only: :create
def create
build_resource(sign_up_params)
resource.save
yield resource if block_given?
if resource.persisted?
# valid resource
else
clean_up_passwords resource
set_minimum_password_length
render json: {user: resource.errors}
end
end
end
end
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << [:first_name, :last_name]
end
end
request:
with headers: Accept - application/json
Started POST "/api/users" for 127.0.0.1 at 2015-07-01 17:05:26 +0300
Processing by Api::Users::RegistrationsController#create as JSON
Parameters: {"user"=>{"email"=>"usermail#gmail.com", "password"=>"[FILTERED]", "first_name"=>"firstName", "last_name"=>"lastName"}}
(0.1ms) BEGIN
(0.1ms) ROLLBACK
Completed 200 OK in 17ms (Views: 0.2ms | ActiveRecord: 3.8ms)
response:
{"user":{"email":["can't be blank"],"password":["can't be blank"],"first_name":["can't be blank"],"last_name":["can't be blank"]}}
Hello friends I have something to confess first,my previous account was banned from asking questions,From now on, i will try to make the questions more clear and precise!
I'm working on Hartl's ruby on rails tutorials ,i have been stuck at chapter 9.2.2 Requiring the right user `"Listing 9.13 Testing that the edit and update actions require the right user" for a few days. I have done lots of research,i went back and forth of the chapters , it didn't work and it seems no one had the issue that i have now . Let me explain in details.
Errors:
Authentication authorization as wrong user submitting a GET request to the Users#edit action
Failure/Error: specify { expect(response.body).not_to match(full_title('Edit user')) }
TypeError:
wrong argument type nil (expected Regexp)
# ./spec/requests/authentication_pages_spec.rb:61:in `block (5 levels) in <top (required)>'
Finished in 1.77 seconds
64 examples, 1 failure
i have tested with the brower,it works perfectly,i tried to edit other users. the page was directed to the home page successfully!
Github: https://github.com/Snailseason2014/Sample
here are some related files:
spec/requests/authentication_pages_spec.rb
require 'spec_helper'
describe 'Authentication' do
subject { page }
describe 'signin page' do
before { visit signin_path }
it { should have_content('Sign in') }
it { should have_title('Sign in') }
end
describe 'signin' do
before { visit signin_path }
describe 'with invalid information' do
before { click_button 'Sign in' }
it { should have_title('Sign in') }
it { should have_selector('div.alert.alert-error', text: 'Invalid') }
describe 'after visiting another page' do
before { click_link 'Home' }
it { should_not have_selector('div.alert.alter-error') }
end
end
describe 'with valid information' do
let(:user) { FactoryGirl.create(:user) }
before { sign_in user }
it { should have_title(user.name) }
it { should have_link('Profile', href: user_path(user)) }
it { should have_link('Settings', href: edit_user_path(user)) }
it { should have_link('Sign out', href: signout_path) }
it { should_not have_link('Sign in', href: signin_path) }
describe 'followed by signout' do
before { click_link 'Sign out' }
it { should have_link('Sign in') }
end
end
end
describe 'authorization' do
describe 'for non-signed-in users' do
let(:user) { FactoryGirl.create(:user) }
describe 'in the Users controller' do
describe 'visiting the edit page' do
before { visit edit_user_path(user) }
it { should have_title('Sign in') }
end
describe 'submitting to the update action' do
before { patch user_path(user) }
specify { expect(response).to redirect_to(signin_path) }
end
end
end
describe 'as wrong user' do
let(:user) { FactoryGirl.create(:user) }
let(:wrong_user) { FactoryGirl.create(:user, email: 'wrong#example.com') }
before { sign_in user, no_capybara: true }
describe 'submitting a GET request to the Users#edit action' do
before { get edit_user_path(wrong_user) }
specify { expect(response.body).not_to match(full_title('Edit user')) }
specify { expect(response).to redirect_to(root_url) }
end
describe 'submitting a PATCH request to the Users#update action' do
before { patch user_path(wrong_user) }
specify { expect(response).to redirect_to(root_url) }
end
end
end
end
app/controllers/users_controller.rb
class UsersController < ApplicationController
before_action :signed_in_user, only: [:edit, :update]
before_action :correct_user, only: [:edit, :update]
def show
#user = User.find(params[:id])
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
sign_in #user
flash[:success] = 'welcome'
redirect_to #user
else
render 'new'
end
end
def edit
# #user = User.find(params[:id])
end
def update
# #user = User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = 'Profile updated'
redirect_to #user
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
# Before filters
def signed_in_user
redirect_to signin_url, notice: 'Please sign in.' unless signed_in?
end
def correct_user
#user = User.find(params[:id])
redirect_to(root_path) unless current_user?(#user)
end
end
It looks like you skipped some of the exercises, specifically the exercises in section 5.6, which would have prevented your error.
In any case, in chapter 5 the tutorial had you define a duplicate full_title() helper for the tests to use, which was to be put in the file:
spec/support/utilities.rb
The original full_title() helper was used by the views.
Looking at your spec/support/utilities.rb file, you have this:
def full_title(page_title)
base_title = 'Ruby on Rails Tutorial Sample App'
if page_title.empty?
base_title
else
"#{base_title} | #{page_title}"
end
Can you see what's wrong? It's obvious that you copy and pasted that code from the text of the tutorial, and you missed the last line which was: end, which is required to close the def you started on the first line. However, I cannot explain why you haven't been getting a SyntaxError when trying to run your tests, which prevents the tests from running at all when I try it.
In your spec:
expect(response.body).not_to match(full_title('Edit user'))
a match exepctation is expected to match some text against a regular expression eg:
expect("hello").to match(/ell/) # => true
expect("hello").to match(/blah/) # => false
full_title('Edit user') is not a regular expression... it's some content on the page. So it really isn't the right thing to use in an expect...match. You can turn any string into a regular expression by putting it inside // and using string-interpolation syntax eg:
a_string = 'some string'
a_regex = /#{a_string}/
so here you could use:
expect(response.body).not_to match(/#{full_title('Edit user')}/)
HOWEVER... the error message you get is indicative of something deeper... it says that you are passing a nil instead of a regular expression... which means that full_title('Edit user') is evaluating to nil instead of an actual string.
if you use my example above... the spec will likely still fail... so you have to figure out why full-title('Edit user') is returning nil and fix that first.
I'm stuck (again!) at Chapter 9 (this time in section 9.2.2) of the Rails tutorial. I am getting
bundle exec rspec spec/
................................FFF........................
Failures:
1) Authentication authorization as wrong user submitting a GET request to the Users#edit action
Failure/Error: before {sign_in user, no_capybara: true}
NoMethodError:
undefined method `new_remember_token' for #<User:0x007f8181815448>
# ./spec/support/utilities.rb:13:in `sign_in'
# ./spec/requests/authentication_pages_spec.rb:71:in `block (4 levels) in <top (required)>'
The other 2 errors are of the same type.
Here is spec causing the errors:
describe "as wrong user" do
let(:user) {FactoryGirl.create(:user)}
let(:wrong_user) {FactoryGirl.create(:user, email: "wrong#example.com")}
before {sign_in user, no_capybara: true}
describe "submitting a GET request to the Users#edit action" do
before {get edit_user_path(wrong_user)}
specify { expect(response.body).not_to match(full_title('Edit user'))}
specify { expect(response).to redirect_to(root_url)}
end
describe "submitting a PATCH request to the Users#update action" do
before { patch user_path(wrong_user)}
specify { expect(response).to redirect_to(root_url)}
end
end
And here is the method (utilities.rb) the error message is complaining about:
def sign_in (user, options={})
if options[:no_capybara]
# Sign in when not using Capybara
remember_token = User.new_remember_token
cookies[:remember_token]
user.update_attribute(:remember_token, User.digest(remember_token))
else
visit signin_path
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Sign in"
end
end
The code for the model (User.rb) is here:
class User < ActiveRecord::Base
before_save { self.email = email.downcase}
before_create :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
validates :password, length: {minimum: 6}
has_secure_password
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.digest(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.digest(User.new_remember_token)
end
end
I had previously trouble with the sign_in method but it miraculously disappeared. What am I doing wrong?
I finally found the culprit for the erratic test results that I have been observing in this case and, quite likely, on previous occasions (Failure/Error: sign_in user undefined method `sign_in', Rails named route not recognized). The problem seems to be that rails does not clear by default the cache between tests. Which is, actually, downright scary. It seems you cannot really trust the test results. I realised this by commenting out the method that rails was complaining about and re-running the test. The error persisted which meant one thing - rspec was simply working with some cached versions of the files and thus disregarding the changes which I am making. So even if the tests pass you can't be sure that they really do. This is really bizarre. After realising the problem with a bit of googling I found how to force rails to clean the cache - check jaustin's answer here: is Rails.cache purged between tests?
I have Rails 4.2.6 and rspec 3.3.0 , devise version 3.5.8 and i have trouble to test my controller specs always getting error saying ("expected the response to have a success status code (2xx) but it was 401")
Later when i try different spec I am always getting failure message ("Your account is not enabled yet !"), any ideas ?, any help much appreciated ..
my spec:
require 'rails_helper'
describe MyController, :type => :controller
let(:user) { create(:user) }
let(:campaign) { create(:campaign, user: user) }
let!(:placement) { create(:placement, user: user, campaign: campaign, end_date: Date.today) }
before(:each) do
sign_in user
end
context "when we have no data" do
before do
get :graph_data, format: :json
#json = JSON.parse(response.body)
end
it "should be a success" do
expect(response).to have_http_status(:success)
end
end
end
I have following spec_helper:
config.include Devise::TestHelpers, :type => :controller
config.before(:each) do
DatabaseCleaner.start
end
factory defined:
FactoryGirl.define do
factory :unconfirmed_user, class: User do
sequence(:email) { |n| "john#{n}#email.com" }
sequence(:name) { |n| "John Nice #{n}" }
password 'password'
password_confirmation 'password'
factory :user do
confirmed_at Time.now.utc
factory :admin do
organisation { create(:organisation, :some_organisation) }
end
end
end
controller:
MyController < ApplicationController
def graph_data
items = current_user.items //outputs [1,2,3,45,5]
render json: items, status: :ok
end
end
routes:
GET /mycontroller/graph_data(.:format)
i found what was the issue,on User model had a method 'active_for_authentication?'
def active_for_authentication?
super && (group.include?('company-group) || is_admin? )
end
Method 'active_for_authentication?' is a Devise public method
and when it is defined in your model like (User), you change behaviour of it, and in my case it was overwritten with different behaviour,
checking for belonging user to the 'company-group' or not ..
That's why i had failure message ("Your account is not enabled yet !")