RSpec controller test error: controller does not implement method - ruby-on-rails

I've written some custom code for Devise registration. Namely once a user hits the "sign up" button, Devise's generic code ensures that the user is saved correctly. But then, I want to go in and make sure that the user gets an associated Stripe customer account. Most of the code below is from Devise, except for a few lines that I added:
class Users::RegistrationsController < Devise::RegistrationsController
def create
build_resource(sign_up_params)
resource.save
yield resource if block_given?
if resource.persisted?
#### If statement below is the key custom code ####
if create_stripe_customer
#### Back to default Devise code ####
if resource.active_for_authentication?
set_flash_message :success, :signed_up if is_flashing_format?
sign_up(resource_name, resource)
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
#### Else statement below is custom ####
else
flash[:danger] = flash_messages["not_your_fault"]
redirect_to root_path
end
else
clean_up_passwords resource
set_minimum_password_length
respond_with resource
end
end
private
def create_stripe_customer
new_stripe_customer = StripeService.new({
source: sign_up_params[:token],
user_id: self.id
})
if new_stripe_customer && self.update_attributes(stripe_customer_id: new_stripe_customer.id)
else
false
end
end
end
I'm trying now to write tests on the create controller to make sure that upon a post to create, my custom method:
Gets the right parameters (i.e., there are other tests to make sure that the method does the right things with those parameters), and returns true, whereby then the user is redirected to the after_sign_up_path. In this example, the right parameter is that the sign_up_params[:token] is being passed through to create_stripe_customer
Gets the wrong parameters and returns false, whereby the user is redirected to the root_path as per my custom code
This is my RSpec file so far:
describe Users::RegistrationsController, "Create action" do
before do
request.env['devise.mapping'] = Devise.mappings[:user]
end
it "Successful creation" do
Users::RegistrationsController.should_receive(:create_stripe_customer).with(source: "test" , user_id: #user.id).and_return(false)
post :create, sign_up: { first_stripe_token: "test" }
end
end
When I run it however, I get:
Failure/Error: Users::RegistrationsController.should_receive(:create_stripe_customer).with(source: "test" , user_id: #user.id).and_return(false)
Users::RegistrationsController does not implement: create_stripe_customer
Not sure why the controller is not implementing the method...

You're stubbing create_stripe_customer as a class method, but it's actually an instance method.

Related

on sign up if email already exist then render user on specific page where i can display some message

i just want to send confirmation instructions to user again if email already exist.
Thats what i've implemented, it just let user to sign Up if email is unique. if email already exist it just don't do anything.
class RegistrationsController < Devise::RegistrationsController
layout 'pages'
def new
build_resource
yield resource if block_given?
respond_with resource
end
def create
build_resource(sign_up_params)
admin = User.create(first_name: "")
resource.authenticatable = admin
resource.save
yield resource if block_given?
if resource.persisted?
if resource.active_for_authentication?
set_flash_message! :notice, :signed_up
sign_up(resource_name, resource)
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
expire_data_after_sign_in!
respond_with resource, location: accounts_get_started_path(resource)
end
else
byebug
clean_up_passwords resource
set_minimum_password_length
respond_with resource
end
end
def edit
super
end
def update
super
end
def destroy
super
end
end
If the email already exists you should resend devise confirmation mail by doing this:
Devise::Mailer.confirmation_instructions(resource).deliver
You can use valid? runs all the validations within the specified context. Returns true if no errors are found, otherwise it returns false. (Refer to this link for more info.)
NOTE: Here I am assuming you have uniqueness validation on email field. (Refer this link for more info)
If you have validation, then your code looks like
def create
build_resource(sign_up_params)
.
.
if resource.valid?
# your code for saving details
else
# Your code to redirct to different page
redirect_to where_you_want
end
end

Ruby/Rails: suppress superclass functions - integration of Stripe and Devise

I have a create method in my RegistrationsController, which inherits from Devise::Registrations controller. It is supposed to call Stripe and if the creation of a customer is successful, it saves the user and sends a confirmation email, which is handled by '#create' in Devise. If the call to Stripe fails, it is supposed to set a flash and not save the user or send an email, i.e. suppress the Devise 'create' method. The method works fine if the call to Stripe is successful, but if it is not successful, the user is still saved and the confirmation email is still sent.
class RegistrationsController < Devise::RegistrationsController
def create
super
#user = resource
result = UserSignup.new(#user).sign_up(params[:stripeToken], params[:plan])
if result.successful?
return
else
flash[:error] = result.error_message
# TODO: OVERIDE SUPER METHOD SO THE CONFIRM EMAIL IS
# NOT SENT AND USER IS NOT SAVED / EXIT THE METHOD
end
end
I have tried skip_confirmation!, this just bypasses the need for confirmation. resource.skip_confirmation_notification! also does not work. I have also tried redefining resource.send_confirmation_instructions; nil; end; My thought was to exit the create method altogether in the else block. How can I exit the create method or suppress 'super' in the else block, or would another approach be better? Thanks.
By calling super at the top of your override, the whole registration process will take place, signing up your user, and only then executing your code.
You need to override Devise's registrations_controller.rb create action code by copy and pasting the whole and inserting your call like this:
class RegistrationsController < Devise::RegistrationsController
# POST /resource
def create
build_resource(sign_up_params)
# Here you call Stripe
result = UserSignup.new(#user).sign_up(params[:stripeToken], params[:plan])
if result.successful?
resource.save
else
flash[:error] = result.error_message
end
yield resource if block_given?
if resource.persisted?
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_flashing_format?
sign_up(resource_name, resource)
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
set_minimum_password_length
respond_with resource
end
end
end
Notice that resource.save is only called if result.successful?.

Nil Current_user in modified Devise create action

I created a custom Registration controller for Devise. I inserted a param in my form that says if it's true I should do some extra stuff after registration, for example, create a related company for the user.
class RegistrationsController < Devise::RegistrationsController
before_filter :authenticate_user!, :only => :token
def new
super
end
def create
super
reg_type = params['reg_type']
if reg_type=='1'
current_user.create_default_company!
end
end
def update
super
end
end
However, my current_user is coming up nil.
undefined method `create_default_company!' for nil:NilClass
What can I use to reference the current_user immediately after super is called, which creates the user.
Params:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"E1urosfkmekwweklo/HZaEVrrmxQVKO9E=", "user"=>{"name"=>"", "email"=>"4#Gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up", "reg_type"=>"1"}
I am passing the parameter, using two links:
new_user_registration_path(reg_type: '0')
new_user_registration_path(reg_type: '1')
The action of the create depends on which link the user chooses.
You can check this reg_type param in after_create callback and then create default company if it is equal to '1'.
If you open devise gem , you will find create method as
(devise-3.2.4)
def create
build_resource(sign_up_params)
if resource.save
yield resource if block_given?
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_flashing_format?
sign_up(resource_name, resource)
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
respond_with resource
end
end
you should first check which version of devise you are using then you can override that method in your controller.
In short using resource instead current_user may solve your problem, but it may generate inappropriate result as you will only assigning attributes (not saving) after rendering template.
You should be able to access the new user by passing a block to super:
def create
super do |resource|
if params['reg_type'] == "1"
resource.create_default_company!
end
end
end
This is explained (well, at least mentioned) in the docs under "Configuring controllers".
The new user is accessible via the block parameter resource, although it might not be saved at this point.
Firstly, thank you for all the comments. My solution was to use andrey deineko suggestion with a after_create call back. I added an attr_accessor to reference the permission, which I added to the form as a hidden field.
I used..
class User < ActiveRecord::Base
attr_accessor :reg_type
after_create :create_default_company!, if: :is_reg?
def is_reg?
#reg_type == '1'
end
...
end
It seems to work well. thank you for all the recommendations.

How to Track Devise User Registration as Conversion in Google Analytics

I'm using Devise with my Rails 3.2 app and I want to be able to add track new registrations as conversions in Google Analytics. I'd like to have the new users directed to the same page that they are being redirected to now, if possible (i.e. may be a pass thru view that redirects to the current page users are redirected to after create).
Can someone please help me figure out the best way to do this with Devise?
# users/registrations_controller.rb
# POST /resource
def create
build_resource
if resource.save
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_navigational_format?
sign_up(resource_name, resource)
respond_with resource, :location => after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
respond_with resource
end
end
def after_sign_up_path_for(resource)
after_sign_in_path_for(resource)
end
From the top of my head, I'd use flash.
The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed to the very next action and then cleared out.
On the registrations_controller.rb:
if resource.active_for_authentication?
flash[:user_signup] = true # or something that you find more appropriate
set_flash_message :notice, :signed_up if is_navigational_format?
sign_up(resource_name, resource)
respond_with resource, :location => after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
Then, on the view that you redirect to after a signup, I'd render the necessary code to trigger a Google Analytics event based on the presence of flash[:user_signup].
You can do it from your controller:
Step 1: in order to keep it organised, you can create a file app/controllers/concerns/trackable.rb with the following content:
module Trackable
extend ActiveSupport::Concern
def track_event(category, action)
push_to_google_analytics('event', ec: category, ea: action)
end
def track_page_view
path = Rack::Utils.escape("/#{controller_path}/#{action_name}")
push_to_google_analytics('pageview', dp: path)
end
private
def push_to_google_analytics(event_type, options)
Net::HTTP.get_response URI 'http://www.google-analytics.com/collect?' + {
v: 1, # Google Analytics Version
tid: AppSettings.google_analytics.tracking_id,
cid: '555', # Client ID (555 = Anonymous)
t: event_type
}.merge(options).to_query if Rails.env.production?
end
end
Step 2: Replace your tracking ID.
Step 3: Finally, track your conversions in your controller:
# app/controllers/confirmations_controller.rb
class ConfirmationsController < Devise::ConfirmationsController
include Trackable
after_action :track_conversion, only: :show
private
def track_conversion
track_event('Conversions', 'from_landing_page')
# or # track_event('Conversions', user.email)
end
end
Extra: you can also use the track_page_view method to track specific actions that don't have views (like API requests).
More info here: https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide.

Devise: redirect on sign up failure?

I'm trying to redirect users that have failed the sign up form (e.g. they entered a username that is already taken, they left a field blank, etc...)
I have custom failure set up for users that fail the sign in form, code below:
class CustomFailure < Devise::FailureApp
def redirect_url
root_path
end
def respond
if http_auth?
http_auth
else
redirect
end
end
However, I've been stuck on how to set this up for sign up failure. Ideally I would just like to redirect them back/to root_path, any ideas? Thank you!
You will probably need to subclass Devise::RegistrationsController and override the create action. Just copy over the create method from here and modify the redirect on failure to save.
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def create
# modify logic to redirect to root url
end
end
Change your routes to tell Devise to use your controller:
# config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}
It's a bit tedious to modify certain parts of devise to suit your needs and I suspect it's because the gem does a good job to cover most common cases. However, edge-cases for use of devise are a lot and your question points to one of them. I had to do something similar, that is, make sure devise redirects to a specific page when a user does one of the following:
submits form on an empty form
submits an already existing email.
Below is how I handled it.
First, create a controller called RegistrationsController that inherits from Devise::RegistrationsController like so:
class RegistrationsController < Devise::RegistrationsController
end
Inside this controller you will have override the create method in devise. Go to the devise github page here, https://github.com/plataformatec/devise/blob/master/app/controllers/devise/registrations_controller.rb to view the create method and copy the code in that method. Then create a private method to override the returning statment of the last block of the if statement. Your controller should look like so,
class RegistrationsController < Devise::RegistrationsController
def create
build_resource(sign_up_params)
resource.save
yield resource if block_given?
if resource.persisted?
if resource.active_for_authentication?
set_flash_message! :notice, :signed_up
sign_up(resource_name, resource)
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
set_minimum_password_length
response_to_sign_up_failure resource
end
end
private
def response_to_sign_up_failure(resource)
if resource.email == "" && resource.password == nil
redirect_to root_path, alert: "Please fill in the form"
elsif User.pluck(:email).include? resource.email
redirect_to root_path, alert: "email already exists"
end
end
end
It should work.
Tip:
To keep flash error messages add this line before the redirect_to in your override
resource.errors.full_messages.each {|x| flash[x] = x}
So in your registrations_controller.rb :
def create
build_resource(sign_up_params)
if resource.save
yield resource if block_given?
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_flashing_format?
sign_up(resource_name, resource)
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
resource.errors.full_messages.each {|x| flash[x] = x} # Rails 4 simple way
redirect_to root_path
end
end
In config/routes.rb:
devise_scope :user do
get '/users', to: 'devise/registrations#new'
end

Resources