Rspec spec fails on the following test case. Can anyone please help me with sending params inside the body?
Test case:
describe 'POST search' do
it 'renders search' do
request.headers['Content-Type'] = 'application/json'
request.headers['Accept'] = 'application/json'
post :search, body: {name: {query_type: 'match', value: ['xy']} }.to_json
expect(response.status).to eq(200)
expect(response.body.include?('TWEEDLE'))
end
end
Controller:
def search
page_params = pagination_params
query_hash = QueryPreprocessor.params_to_query_with_types(JSON.parse(request.body.read).deep_symbolize_keys)
logger.info "query_hash: #{query_hash}"
es_query_json = Elastic::QueryBuilder.facility_search_v1(query_hash, page_params).to_json
logger.info "es query: #{es_query_json}"
facilities = facility_helper.search es_query_json
json_response build_facilities_response(facilities)
rescue ApiError => e
render json: e.response, status: e.status
end
and these are the params which I want to include inside the body, which is being called in the controller:
def pagination_params
page_params = {}
page_params['size_params'] = params[:size] || 50
page_params['from_params'] = params[:from] || 0
page_params['sort_params'] = params[:sort]
page_params['order_params'] = params[:order]
page_params
end
Rspec should passes, with pagination params included inside the body.
You can POST json with "as: :json".
describe 'POST search' do
it 'renders search' do
request.headers['Content-Type'] = 'application/json'
request.headers['Accept'] = 'application/json'
post :search, params: {name: {query_type: 'match', value: ['xy']} }, as: :json
expect(response.status).to eq(200)
expect(response.body.include?('TWEEDLE'))
end
end
Related
In my controller specs everything works fine (update action, edit action, etc. also via js request), except the create action. For some reason it doesn't change the Task.count, but the http response is 200.
There are no other callbacks and in dev ENV it saves the task in the db. This factory passes in model spec. I also tried to comment out the Notification.create, TaskCreatorJob and Conversation.create.., but didn't help. In my other controller specs the expect { create_action }.to change{Class.count}.by(1) works properly.
What did I miss?
conroller
def create
#task = Task.new(task_params)
#task.assigner_id = current_user.id
if #task.save
Notification.create(recipient_id: #task.executor_id, sender_id: current_user.id, notifiable: #task, action: "assigned")
TaskCreatorJob.perform_later(#task, #task.executor, #task.assigner)
Conversation.create_or_find_conversation(#task.assigner_id, #task.executor_id)
respond_to do |format|
format.js
end
else
respond_to do |format|
format.js
end
end
end
factory
factory :task do
content { Faker::Lorem.sentence }
deadline { Faker::Time.between(DateTime.now + 2, DateTime.now + 3) }
association :executor, factory: :user
association :assigner, factory: :user
end
tasks_controller_spec.rb
.....
before(:each) do
login_user
end
describe "POST create" do
context "with valid attributes" do
let!(:user) { create(:user) }
let!(:profile) { create(:profile, user: #user) }
let!(:profile_2) { create(:profile, user: user) }
let!(:conversation) { create(:conversation, sender: #user, recipient: user) }
subject(:create_action) { xhr :post, :create, user_id: #user.id, task: attributes_for(:task, assigner: #user, executor: user) }
it "saves the new task in the db" do
expect{ create_action }.to change{ Task.count }.by(1)
end
it "responds with success" do
create_action
expect(response).to have_http_status(200)
end
end
end
It seems in controller spec it's not enough to define task params like assigner: #user, so I had to change
subject(:create_action) { xhr :post, :create, user_id: #user.id, task: attributes_for(:task, assigner: #user, executor: user) }
to
subject(:create_action) { xhr :post, :create, user_id: #user.id, task: attributes_for(:task, assigner_id: #user.id, executor_id: user.id) }
I need to pass params in a redirect_to method to an external url...
I know that I can do something like this with a redirect:
redirect_to my_url_path(param1: "foo", param2: "bar")
But I want to do this with an external url. For example:
redirect_to "www.example.externaldomain.com/process/XIGHTDJTRIDEOR", param1: "foo", param2: "bar"
You can use the ruby URI module and create your own helper:
def generate_url(url, params = {})
uri = URI(url)
uri.query = params.to_query
uri.to_s
end
Then just get the url:
redirect_to generate_url("www.example.externaldomain.com/process/XIGHTDJTRIDEOR", :param1 => "foo", :param2 => "bar")
I'm trying to implement infinite scrolling into my project.
I have do everything as in this howto: https://github.com/amatsuda/kaminari/wiki/How-To:-Create-Infinite-Scrolling-with-jQuery
But it's not working for me :(
Controller:
def show
category = Category.find(params[:id])
products = category.products.page(params[:page])
#category = CategoryDecorator.decorate(category)
#products = ProductDecorator.decorate_collection(products)
respond_to do |format|
format.js
format.html
format.xml { render :xml => #products }
end
end
show.html.haml:
#products_list
%page
= render 'products_list'
:javascript
$(function() {
var page = 1,
loading = false;
function nearBottomOfPage() {
return $(window).scrollTop() > $(document).height() - $(window).height() - 200;
}
$(window).scroll(function(){
if (loading) {
return;
}
if(nearBottomOfPage()) {
loading=true;
page++;
$.ajax({
url: '/universes/nautique/sports/surfwear/categories/boarshorts?per_page=' + page,
type: 'get',
dataType: 'script',
success: function() {
$(window).sausage('draw');
loading=false;
}
});
}
});
$(window).sausage();
}());
- content_for :javascript do
= javascript_include_tag "jquery.sausage"
Partial _products_list.html.haml:
- #products.each_with_index do |product,index|
.block-prodlist{ data: { index: product.id } }
.inner.onfocus
.selection
%label AJOUTER À MA SÉLECTION
%input.chk{:name => "", :type => "checkbox", :value => ""}/
.thumbproduit
= index
%img{:alt => "Produit", :height => "194", :src => "/assets/editorial/produit1.jpg", :width => "194"}/
.prixcaption -20%
.context
%h3
= product.brand_name
And show.js.haml:
$("#products_list").append("#{escape_javascript(render(#products))}");
I don't see show.js in my firebug.
Error was with store script - show.js.haml
I have change #products to my partial name:
$("#products_list").append("#{escape_javascript(render('products_list'))}");
I've spent the last day trying to get this to work in my Rails app, but continually get the response:
{"code"=>"E-C-343", "message"=>"Unrecognized JSON Request."}
BancBox's Documentation is pretty light, so I'm at a bit of an impasse on how to solve this.
Does anyone have an example of a successful API call to createClient at BancBox utilizing REST?
My Post API call utilizing HTTParty:
include HTTParty
format :json
def save_with_bancbox(params = {})
post_params = { :authentication => { :apiKey => BANCBOX_KEY,
:secret => BANCBOX_SECRET
},
:subscriberId => BANCBOX_ID,
:firstName => params[:first_name],
:lastName => params[:last_name],
:ssn => params[:ssn],
:dob => params[:dob],
:address => { :line1 => params[:address_line_1],
:line2 => params[:address_line_2],
:city => params[:city],
:state => params[:state],
:zipcode => params[:zipcode]
},
:homePhone => params[:dob],
:email => params[:email]
}
response = HTTParty.post( BANCBOX_REST_URL,
:body => post_params)
logger.debug "Response -- #{response}"
save!
end
Please try the below code after changing apikey, secret and subscriberid
require "net/https"
require 'rubygems'
require 'json'
require 'httparty'
###########################bancbox.rb in config/initializers#################
BANCBOX_API_KEY = "__KEY__"
BANCBOX_API_SECRET = "__SECRET__"
BANCBOX_SUBSCRIBER_ID = "__SUB_ID__"
BANCBOX_API_URL = "https://sandbox-api.bancbox.com/BBXPortRest"
module Bancbox
class API
include HTTParty
debug_output $stdout
base_uri "#{BANCBOX_API_URL}"
def initialize(u=BANCBOX_API_KEY,p=BANCBOX_API_SECRET)
auth = {:apiKey => u, :secret => p}
#options = {:body => {:authentication =>auth,:subscriberId=>BANCBOX_SUBSCRIBER_ID}, :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }}
end
#USERS
def create_client(options={})
options = options.merge(#options[:body])
#options.merge!({:body => options.to_json})
response = self.class.post("/createClient",#options)
#required_fields- subscriberId,firstName,lastName,ssn,dob,address,homePhone,email
end
def get_schedules(options={})
#options.merge!({:query => {:subscriberId => BANCBOX_SUBSCRIBER_ID}})
#options.merge!({:query => options})
self.class.post("/getSchedules",#options)
end
end
end
b = Bancbox::API .new
b.create_client({:firstName=> "Bipen",:lastName=> "Sasi",:ssn=>"334-444-4444",:dob=> Date.parse("January 1st 1988"), :address=>{:line1=> "4408 walnut st", :line2=>"apt 3r",:city=> "philly",:state=>"pa",:zipcode=>"19110"}, :homePhone=> "2672551161",:email=>"bipen#lokalty.com"})
I think you should POST the request to
https://sandbox-api.bancbox.com/BBXPortRest/createClient
instead of
https://sandbox-api.bancbox.com/BBXPortRest/
Also make sure to set the content type as application/json
In general, you post your request to https://sandbox-api.bancbox.com/BBXPortRest/<method>
I'm working with Ruby On Rails 3, and I would like to do the following, but from the code behind:
<% form_tag "https://www.sandbox.paypal.com/cgi-bin/webscr" do %>
<%= hidden_field_tag :cmd, "_s-xclick" %>
<%= hidden_field_tag :encrypted, #cart.paypal_encrypted(products_url, payment_notifications_url) %>
<p><%= submit_tag "Checkout" %></p>
<% end %>
I've tried this in my Cart model, but it's not redirecting anywhere, and I don't know what to do:
PAYPAL_CERT_PEM = File.read("#{Rails.root}/certs/paypal_cert.pem")
APP_CERT_PEM = File.read("#{Rails.root}/certs/app_cert.pem")
APP_KEY_PEM = File.read("#{Rails.root}/certs/app_key.pem")
PANEL = 'sandbox.paypal.com'
PATH = '/cgi-bin/webscr'
USERAGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.1) Gecko/20060111 Firefox/1.5.0.1'
def paypal_url(order_id, return_url, notify_url)
http = Net::HTTP.new(PANEL, 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
# GET request -> so the host can set cookies
resp, data = http.get2(PATH, {'User-Agent' => USERAGENT})
cookie = resp.response['set-cookie'].split('; ')[0]
values = {
:cmd => '_s-xclick',
:encrypted => paypal_encrypted(order_id, return_url, notify_url)
}
#headers = {
'Cookie' => cookie,
'Referer' => 'https://'+PANEL+PATH,
'Content-Type' => 'application/x-www-form-urlencoded',
'User-Agent' => USERAGENT
}
resp, data = http.post2(PATH, values.to_query, #headers)
end
def paypal_encrypted(order_id, return_url, notify_url)
values = {
:business => 'seller_1234111143_biz#asciicasts.com',
:cmd => '_cart',
:upload => 1,
:return => return_url,
:invoice => order_id.to_s,
:notify_url => notify_url,
:currency_code => "USD"
}
items.each_with_index do |item, index|
values.merge!({
"amount_#{index + 1}" => item.unit_price,
"item_name_#{index + 1}" => item.product.title,
"item_number_#{index + 1}" => item.product.id + Time.now.to_i,
"quantity_#{index + 1}" => item.quantity.to_i
})
end
encrypt_for_paypal(values)
end
def encrypt_for_paypal(values)
signed = OpenSSL::PKCS7::sign(OpenSSL::X509::Certificate.new(APP_CERT_PEM), OpenSSL::PKey::RSA.new(APP_KEY_PEM, ''), values.map { |k, v| "#{k}=#{v}" }.join("\n"), [], OpenSSL::PKCS7::BINARY)
OpenSSL::PKCS7::encrypt([OpenSSL::X509::Certificate.new(PAYPAL_CERT_PEM)], signed.to_der, OpenSSL::Cipher::Cipher::new("DES3"), OpenSSL::PKCS7::BINARY).to_s.gsub("\n", "")
end
If you're wondering why I can't just use the html form, that's because I let users choose between more than one payment option, using radio fields, and once they have selected one, they will click on the "Submit Order" button, generating the respective movements in my database, before redirecting to the payment method.