I'm writing a Rails API and am stuck trying to write controllers that will test the authentication. For instance, I have in my PostController before_action :authenticate which is
def authenticate
authenticate_or_request_with_http_token do |token, options|
User.find_by(:auth_token => token)
end
end
And this is my PostsController test:
require 'rails_helper'
RSpec.describe Api::PostsController, type: :controller do
let(:valid_attributes) {
{
"title" => "Post title",
"content" => "Post content",
"status" => "published"
}
}
let(:invalid_attributes) {
{
"title" => "",
"content" => "",
"status" => ""
}
}
let(:valid_session) { {} }
before do
params = { session: { email: 'wagner.matos#mac.com', password: 'foobar' } }
SessionsController.create params
#post = Post.new({
title: "Some title",
content: 'Some content',
status: "published"
})
end
it "creates a new post" do
post :create, post: #post
expect(Post.count).to eq(1)
end
end
Yet the above is failing with the following error:
1) Api::PostsController creates a new post
Failure/Error: SessionsController.create params
NoMethodError:
undefined method `create' for SessionsController:Class
Any suggestions?
You can not invoke create action of SessionsController with class. Better you create user object and assign to request.env the same token. like below sample code -
require 'rails_helper'
RSpec.describe Api::PostsController, type: :controller do
before do
user = User.create( :auth_token => 'token' )
request.env["HTTP_AUTHORIZATION"] = ActionController::HttpAuthentication::Token.encode_credentials("token")
end
end
Related
I am trying to write specs for a controller but my tests don't seem to be hitting the controller action.
My controller:
class CoursesController < ApplicationController
def elearning_course_removal
Rails.logger.warn("warning!")
study_group = StudyGroup.where(id: params[:study_group_id]).first
course = Course.where(id: params[:id]).first
if study_group && course
Workflow.new.remove_elearning_course(study_group, course, current_user.id)
flash[:notice] = t('study_groups.courses.remove_elearning_course.enqueue', course_name: course.name)
else
Rails.logger.error(elearning_removal_error(study_group, course))
flash[:notice] = t('study_groups.courses.remove_elearning_course.enqueue_failure')
end
redirect_to :back
end
end
My test:
require 'spec_helper'
describe CoursesController do
describe '#elearning_course_removal' do
let(:course) { FactoryBot.create(:course_with_files) }
let(:study_group) { FactoryBot.create(:study_group) }
let(:user) { FactoryBot.create(:user) }
let(:params) { {study_group_id: study_group.id, id: course.id, current_user: user} }
it 'logs' do
expect(Rails.logger).to receive(:warn)
# put :elearning_course_removal, params
controller.elearning_course_removal
end
end
Calling the route like this put :elearning_course_removal, params in the spec just fails saying that logger wasn't called. Using the second style, controller.elearning_course_removal will hit my controller method, but it's not standard, and I don't know how I would pass params in this case. Its not a routing issue, as it is identifying the controller variable correctly.
What do I need to be able to write request specs for this controller?
I think that you are not sending properly the params
RSpec.describe CoursesController do
describe "GET elearning_course_removal" do
let(:course) { FactoryBot.create(:course_with_files) }
let(:study_group) { FactoryBot.create(:study_group) }
let(:user) { FactoryBot.create(:user) }
let(:params) { {study_group_id: study_group.id, id: course.id, current_user: user} }
it "logs" do
expect(Rails.logger).to receive(:warn)
put :elearning_course_removal, params: params
end
end
you can pass params like this
params: {study_group_id: study_group.id, id: course.id, current_user: user}
params: params
or directly
put :elearning_course_removal, params: {study_group_id: study_group.id, id: course.id, current_user: user}
what you are doing is this
put :elearning_course_removal, {study_group_id: study_group.id, id: course.id, current_user: user}
params tag is missing which could be the issue
I have a rails backend api application integrated with auth0 service that only verifies validity of auth_token received from frontend application. After securing all backend api endpoints all my tests fail with a result "Not Authenticated", which is how it should be. However I cannot figure out how to get through the authentication and to not require it for rspec tests. Here are my classes:
projects_controller_spec.rb
require "rails_helper"
RSpec.describe Api::V1::ProjectsController, :type => :controller do
describe 'GET /api/v1/organizations/1/projects' do
let!(:organization) { create(:organization_with_projects) }
before { get :index, params: { organization_id: organization } }
context 'when authorized' do
it 'should return JSON objects' do
expect(json['projects'].count).to equal(3)
end
it { expect(response).to have_http_status(:ok) }
it { expect(response.content_type).to include('application/json') }
end
describe 'POST /api/v1/organizations/1/projects' do
let!(:organization) { create(:organization) }
let(:project) { organization.projects.first }
before { post :create, params: { organization_id: organization, project: attributes_for(:project) } }
context 'when authorized' do
it { expect(response).to have_http_status(:created) }
it { expect(response.content_type).to include("application/json") }
it { expect(json).to eq(serialized(project)) }
end
end
end
application_controller.rb
class ApplicationController < ActionController::API
include Pundit
include Secured
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
private
def record_not_found(error)
render json: { error: error.message }, status: :not_found
end
end
concerns/secured.rb
module Secured
extend ActiveSupport::Concern
included do
before_action :authenticate_request!
end
private
def authenticate_request!
# Create user if not existing
pundit_user
auth_token
rescue JWT::VerificationError, JWT::DecodeError
render json: { errors: ['Not Authenticated'] }, status: :unauthorized
end
def http_token
if request.headers['Authorization'].present?
request.headers['Authorization'].split(' ').last
end
end
def auth_token
JsonWebToken.verify(http_token)
end
def pundit_user
User.create_from_token_payload({token: auth_token[0], organization_id:
request.parameters['organization_id']})
end
end
lib/json_web_token.rb
require 'net/http'
require 'uri'
class JsonWebToken
def self.verify(token)
JWT.decode(token, nil,
true, # Verify the signature of this token
algorithm: 'RS256',
iss: 'https://xxx.auth0.com/',
verify_iss: true,
aud: Rails.application.secrets.auth0_api_audience,
verify_aud: true) do |header|
jwks_hash[header['kid']]
end
end
def self.jwks_hash
jwks_raw = Net::HTTP.get URI("https://xxx.auth0.com/.well-known/jwks.json")
jwks_keys = Array(JSON.parse(jwks_raw)['keys'])
Hash[
jwks_keys
.map do |k|
[
k['kid'],
OpenSSL::X509::Certificate.new(
Base64.decode64(k['x5c'].first)
).public_key
]
end
]
end
end
It looks like I found a solution by adding the following line into every controller spec file:
before { allow(controller).to receive(:authenticate_request!).and_return(true) }
I'm having trouble passing my params into a nested route through rspec. I'm using Rails 5 and Rspec 3.5
My spec looks like this:
require 'rails_helper'
describe "POST /api/v1/companies/:company_id/products.json", type: :controller do
let!(:user) { create(:company_user, address: create(:address)) }
let!(:company) { create(:company, company_user: user) }
let!(:product) { create(:product) }
let!(:params) { FactoryGirl.attributes_for(:product) }
before do
#controller = Api::V1::ProductsController.new
end
context "company_user signed in" do
before do
auth_headers = user.create_new_auth_token
request.headers.merge!(auth_headers)
sign_in user
end
it 'creates a new product' do
post :create, { company_id: company.id }, { params: {product: product_params} }
expect(response.status).to eq(200)
expect(Product.count).to eq(1)
end
end
end
and in my controller my params look like this:
[1] pry(#<Api::V1::ProductsController>)> params
=> <ActionController::Parameters {"company_id"=>"1", "controller"=>"api/v1/products", "action"=>"create"} permitted: false>
Does anyone know why my product params are not being passed in?
The first Hash is the params for the test:
Try it:
post :create, { company_id: company.id, product: product_params }
i'm writing the code to get my Rspec tests to pass on my api. I'm using the apipie gem to generate documentation and it seems that my tests are failing because thy are expecting a number and it's funny because this is exactly what I want to test.
The page fails when the :bpm parameter is not a number. is there any way of going around this ?
context "when is not created" do
before(:each) do
user = FactoryGirl.create :user
#invalid_lesson_attributes = { title: "California Dreamin",
bpm: "Hello"
}
request.headers['Authorization'] = user.auth_token
post :create, { user_id: user.id, lesson: #invalid_lesson_attributes }
end
it "renders an errors json" do
lesson_response = json_response
expect(lesson_response).to have_key(:errors)
end
it "renders the json errors on why the user could not be created" do
lesson_response = json_response
expect(lesson_response[:errors][:bpm]).to include "is not a number"
end
it { should respond_with 422 }
end
end
Update spec:
context "when is not updated" do
before(:each) do
patch :update, { user_id: #user.id, id: #lesson.id,
lesson: { bpm: "ten" }, format: :json }
end
it "renders an errors json" do
lesson_response = json_response
expect(lesson_response).to have_key(:errors)
end
it "renders the json errors on why the user could not be updated" do
lesson_response = json_response
expect(lesson_response[:errors][:bpm]).to include "is not a number"
end
it { should respond_with 422 }
end
in my users_controller:
api :POST, '/teachers/:user_id/lessons/', "Create lesson"
param :lesson, Hash, desc: 'Lesson information', :required => true do
param :title, String, desc: 'Title of the lesson', :required => true
param :bpm, :number, desc: 'tempo of the lesson (beats per second)', :required => true
end
error :code => 422, :desc => "Unprocessable Entity"
my error when I run my rspec tests :
Apipie::ParamInvalid: Invalid parameter 'bpm' value "Hello": Must be a number.
Adds format json to post request
post :create, { user_id: user.id, lesson: #invalid_lesson_attributes, format: :json }
That worked for me.
I receive following error:
Output:
1) LabelsController#create label is new creates a new label
Failure/Error: post :create, attributes[:label], format: :json
NoMethodError:
undefined method `save!' for nil:NilClass
# ./app/models/labeling.rb:17:in `update_target'
In Labeling model:
after_create :update_target
def update_target
self.target.save!
end
Test:
require 'spec_helper'
describe LabelsController do
before(:each) do
controller.stub(:current_user).and_return(mock_model(User))
stub_request(:any, "www.example.com").to_return(status: 200)
end
describe "#create" do
context "label is new" do
it "creates a new label" do
attributes = {
label: {
name: "test",
labeling: {
target_type: "Link", target_id: 1
}
}
}
response.status.should == 200
post :create, attributes[:label], format: :json
end
end
end
end
Labeling controller:
def create
label = Label.find_by_name(params[:name])
labeling = label.labelings.build do |lb|
lb.user_id = current_user.id
lb.target_type = params[:labeling][:target_type]
lb.target_id = params[:labeling][:target_id]
end
if labeling.save
render json: {
name: label.name,
id: label.id,
labeling: {
id: labeling.id
}
}
end
end
By the looks of it you don't have a Target with ID 1 on the database, so where you refer to self.target the returned value is nil.
What I'd do in your case is first create a target and then pass its id to the attributes hash:
target = Traget.create!
attributes = {
label: {
name: "test",
labeling: {
target_type: "Link", target_id: target.id
}
}
}
This way you don't need to stub anything.
If you really must stub the method you can use RSpecs any_instance method:
Labeling.any_instance.stub(:update_target).and_return(true)