How to test destroy failure in ruby-on-rails - ruby-on-rails

everyone.
I'm gonna test an active record object destroy failure but I've problems creating a failure situation.
I have a before_filter method called 'require_user_payment_info' which validates the #payment_info object before the delete method is called, so I can't create a 'bad' #payment_info object before the delete method is called.
Here's the require_user_payment_info method:
def require_user_payment_info
#payment_info = credit_card_model.slave.find_by_user_guid(user_guid)
if !#payment_info || #payment_info.user_guid != user_guid
redirect_to(:controller => 'store', :action => 'index') and return false
else
if((#payment_info.card_expires_year.to_i < Date.today.year) ||
((#payment_info.card_expires_month.to_i < Date.today.month) && (#payment_info.card_expires_year.to_i == Date.today.year)))
#payment_info.card_account_public = "" #clear this out so the user is forced to re-enter the credit card number
#payment_info.valid?
flash.now[:error] = t('ui_flash_errors.card_expired_error')
end
end
end
And the actual delete method:
def delete
# required to be called via a delete request
redirect_to :action => 'edit' and return if !request.delete?
if #payment_info.destroy
flash[:notice] = "Delete SUCCESSFUL"
redirect_to :action => 'new'
else
flash[:error] = "Delete failed"
redirect_to :action => 'edit'
end
Any ideas?

This is my solution:
def test_delete
payment_info = Factory.create(:payment_info, :user_guid=>#user.guid, :card_expires_month=>'04',
:card_expires_year=>(Date.today.year+2).to_s, :cardholder_city=>"test city",
:cardholder_state=>'NC', :cardholder_country=>'US', :cardholder_zip=>'27612')
PaymentInfo.any_instance.stubs(:destroy).returns(false)
delete(:delete, {}, #session)
assert_response(:redirect)
assert_equal false, assigns(:payment_info).blank?
assert_redirected_to({:controller=>'account', :action=>'edit'})
assert_equal flash[:error], "There was an error deleting your credit card information. Please try again."
end

Related

Session was not persisted after redirect in rails 5

I try to save my variable in an action to call it from another action in my controller. I use session to save it like below:
def upload_with_dropzone
if params[:document]
#resume = #p.documents.new(document_params)
if verify_recaptcha(model: #resume)
#resume.save
session[:resume_id] = #resume.id
redirect_to prospect_upload_path
else
flash[:error] = "Cannot upload image"
redirect_to prospect_upload_path
end
end
In other action I call session[:resume_id] but it return nil
def upload_resume
if session[:resume_id].present?
#resume = Document.find(session[:resume_id])
elsif params[:interaction] && (1..5).include?(params[:interaction][:interaction_rating].to_i)
#resume = #p.documents.last
#itr.update(interaction_feedback_params)
else
#resume = #p.documents.new
end
end
Below is my routes.rb:
match "/upload" => "upload#upload_resume", via: [:get, :post]
post "/upload_resume" => "upload#upload_via_dropzone"
Something was wrong, please give me an idea!
I put byebug after session[:resume_id] = #resume.id line, and I debug the session[:resume_id]

How to use reload without validations?

I'm setting up basic tests for a rails app, I'm wondering how the reload function works. Rails generated the basic crud tests, I adapted them to my need, but it seems like the reload function doesn't work.
I create a user with valid params, then ask to change its name, but it seems like nothing's updated (output is still name: 'Toto' instead of name: 'Tata').
Here's the code sample, I just followed the basic rspec tutorial, still, nothing gets updated. Any idea why ?
context "with valid params" do
let(:new_attributes) { {name: 'Tata'} }
it "updates the requested creator" do
creator = Creator.create! valid_attributes
puts creator.id
puts new_attributes
put :update, :id => creator.id, :creator => new_attributes
creator.reload
puts creator.name.to_yaml
expect(creator.attributes).to include( { "name" => 'Tata' } )
...
Here's the matching controller method
def update
#creator = Creator.find(params[:id])
authorize #creator
#creator.completed = true
params[:hidden] == 'false' ? #creator.hidden = false : #creator.hidden = true
#creator.update(creator_params)
if params[:user].present?
if params[:user][:picture].present?
#creator.picture = params[:user][:picture]
end
end
if #creator.save
if iban.nil? || (iban && !iban.valid?)
flash[:alert] = "Veuillez entrer un IBAN valide"
redirect_to edit_creator_path(#creator)
elsif params[:brief_id].present?
flash[:notice] = "Informations mises à jour"
redirect_to brief_path(params[:brief_id])
else
flash[:notice] = "Informations mises à jour"
redirect_to creator_path(#creator)
end
else
puts #creator.errors.full_messages
render :edit
end
end

Why Rails redirects to the /create page?

I have the next create action in feed_controller:
def create
#feed = Feed.new(check_params)
#new_feed = Feed.new(check_params)
#feed.member_id = current_user.member.id
if params[:commit] == "Upload Video"
if #feed.save
now_is = User.select("uploadLimit").where("email" => session[:email]).last.uploadLimit
User.update(session[:id], :uploadLimit => now_is.to_i - 1)
redirect_to "/#{params[:locale]}/feed"
flash[:notice] = "Congratulations! Your media file has been added!"
else
redirect_to "/#{params[:locale]}/feed"
flash[:notice] = "Oops! Something went wrong!"
end
end
end
And my routes.rb is:
post '/:locale/feed/create', to: "feed#create"
get '/:locale/feed/new', to: "feed#new", as: 'feed_new'
So, my question is, why it redirects to the /create but not to the redirect_to "/#{params[:locale]}/feed page? It works yesterday, but today I'm checking now it ceased to work. Who knows, what is the problem?

Getting AbstractController::DoubleRenderError:

def purchase
...
perform_payment_post
redirect_to :action => 'billing'
...
end
def perform_payment_post
params[:coverages] ||= {}
params[:customer][:coverage_addon] = (params[:coverages].collect { |k,v| k }).join(', ')
params[:customer][:coverage_ends_at] = 1.year.from_now
Rails.logger.info("--- id = #{cookies.signed[:incomplete_gaq_customer_id]}")
id = cookies.signed[:incomplete_gaq_customer_id]
return redirect_to :action => #is_affiliate_user ? 'affiliate':'quote' if id.nil?
#customer = Customer.find(cookies.signed[:incomplete_gaq_customer_id])
return redirect_to :action => 'please_call' if #customer.status_id != 0
#customer.update_attributes(params[:customer])
#customer.notes.create({ :notes_text => #note }) if #note
if params[:property_id].to_i == 0 then #customer.properties.create(params[:property]) end
end
Getting Error on purchase method on line redirect_to :action => "billing".
AbstractController::DoubleRenderError: Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".
Please Help Me.
If you want to return early in controller you either need to write it like this
redirect_to(:action => #is_affiliate_user ? 'affiliate':'quote') and return if id.nil?

Rails regex validations throw no method error in Heroku

I have used the following regex to validate the nic number in my rails app :
VALID_NIC_REGEX = /\A\d{9}[V|v|x|X]\z/i
validates :nic, presence: true, allow_blank: true, format: { with: VALID_NIC_REGEX }, uniqueness: { case_sensitive: false }
When I test it in my local machine, everything works fine. But after uploading to heroku, it give an error while trying to save the member with a value in the nic field. Both valid and invalid values give the error. If there's no value in the nic field, it saves the member. In the heroku log, I found this error :
NoMethodError (undefined method `limit' for nil:NilClass):
app/controllers/members_controller.rb:117:in `update'
So, I commented out the two validation lines and uploaded the site to Heroku. Now it works. Can some one please explain this? Thank you.
Controller update action :
def update
#source = params[:source]
#telfie = params[:telfie].to_i
#member = Member.find(params[:id])
#tel = Array.new
(1..#telfie.to_i).each do |i|
#tel << params[:tele][:"#{'tele'}#{i}"]
end
#params[:tele] = #tel
if params[:commit] == 'More Numbers'
#telfie = #telfie + 1
render 'edit'
else
if params[:commit] == 'Less Numbers'
if #telfie > 1
#telfie = #telfie - 1
render 'edit'
else
flash.now[:error] = "Can't remove all contact fields!"
render 'edit'
end
else
if #member.update_attributes(member_params)
#member.tele = #tel
#member.save
flash[:success] = "Member #{#member.name} Successfully Updated!"
if params[:commit] == 'Save Member and Add Associates'
redirect_to new_associate_url(memberid: #member.id, source: "memberv" )
else
if #source == "database"
redirect_to database_path
else
redirect_to member_url(#member)
end
end
else
render 'edit'
end
end
end
end

Resources