trying to do a query session for Parse - ruby-on-rails

using the gem parse-ruby-client and im trying to do a query session, here is my code.
im just curious on how to implement most of the https://parse.com/docs/rest/guide. Also i dont know if i created a session to begin with? i think the gem does it automatically? not too sure
class LoginController < ApplicationController
def index
end
def log_in
user = Parse::User.authenticate(params[:user][:username], params[:user][:password])
#username = params[:user][:username]
rescue Parse::ParseProtocolError
redirect_to :controller => "login"
end
def logout
Parse.client.post("https://api.parse.com/1/logout", {})
rescue Parse::ParseProtocolError
redirect_to :controller => "login"
end
def query_session
Parse.client.post("https://api.parse.com/1/users/", {})
end
end
here is log_in.html.erb
<h4>You are logged in as: <u><%= #username %></u></h4>
<%= link_to "logout", :controller => "login", :action => 'logout' %><br>
<%= link_to "test", :controller => "login", :action => 'query_session' %>
routes.rb
Rails.application.routes.draw do
root 'login#index'
get 'login/log_in' => 'login#log_in'
post 'login/log_in' => 'login#log_in'
get 'login/logout'
get 'login/query_session' => 'login#query_session'
end
this is my parse.rb
require 'parse-ruby-client'
Parselogin::Application.configure do
config.parse = Parse.init :application_id => 'APIKEY',
:api_key => 'APIKEY'
end
i get back this error when i click on 'test' button from the log_in.html.erb
201: missing user password

You are missing the initialization of the Parse.client. This is an example from the gem's official documentation.
require 'parse-ruby-client'
client = Parse.create :application_id => '<your_app_id>',
:api_key => '<your_api_key>',
:quiet => true | false
To use the client later on, do the actions like this.
client.post("https://api.parse.com/1/logout", {}), where client is the variable from 1st snippet.
In order to respond to the second part of your question, please consider the gem's documentation.

Related

Request in Rails Testing not returning body

I'm starting to do some testing to my app in rails, and following official tutorial, I've written this:
class UserFlowTest < ActionDispatch::IntegrationTest
def login
post ns_login_user_path, { :user => { :username => 'user', :password => 'password' } }
assert_response 200
end
test "should complete a flow" do
login
post create_participant_path(:event_id => events(:myevent).id), {
:format => :json,
:event_role => event_roles(:regular_participant).id,
:in_team => true
}
r = JSON.parse(response.body)
assert_response 200
puts "response creating participation #{r.as_json}"
participant_id = r[:participant_id]
end
end
It does the login OK, but after that, when trying to create the participant, response is a variable with no .body attribute, just the number 200 (the status), so the JSON.parse method crashes.
This is the relevant part of my routes.rb:
# Events
scope 'events', :controller => :events do
# some routes
scope ':event_id', :controller => :events do
# some routes
scope 'participants', :controller => :participants do
post '', :action => :create_participant, :as => :create_participant
# some routes
end
end
end
And the controller ParticipantsController.rb:
class ParticipantsController < ApiController
before_action :require_login, :only => [:create_participant, :update_participant]
# Creates a participation of a person in the event
# Receives the following params:
# - +event_id+
# - +in_team+::_boolean
# - +event_role+
def create_participant
# … some logic
if participant.save
render :status => :ok, :json => Hash[
:participant_id => participant.id,
:team_participant_id => participant.team_participant_id
]
else
render :status => 406, :json => Hash[
:message => t('alerts.error_saving'),
:errors => participant.errors.as_json
]
end
end
end
I've seen the full response object on controller specs, but looking at the code, it appears that the ActionDispatch::IntegrationTest code only returns the response.status, not the entire response object.
The documentation doesn't directly say that you can access the response object. You might try doing a render_views and see if that makes any difference, but based on inspection of the code, it doesn't seem like it will.

Requests spec post request No route matches error

I'm getting no route matches with rspec for testing a method in my controller.
Below is the test code:
let(:csv_file){ fixture_file_upload('files/sample_employee_data.csv', 'text/csv') }
describe "#process_csv" do
it "should output a valid csv file" do
post '/payslips/process_csv', :csv => csv_file, :header => 1
puts response
end
end
Below is my routes.rb file code:
PayCalculator::Application.routes.draw do
resources :payslips do
collection { post :process_csv }
end
root 'payslips#index'
end
Below is the method
def process_csv(uploaded_file = params[:files][:csv], headers = params[:files][:headers])
begin
rows = CSV_Manager.extract_csv(uploaded_file, headers)
rows.each do |row|
payslip = Payslip.create(
:first_name => row[0],
:last_name => row[1],
:annual_salary => row[2],
:superannuation => row[3].to_i,
:payment_start_date => row[4]
)
redirect_to root_url, notice: payslip.errors.full_messages and return unless payslip.valid?
prepare_output(row)
end
#rows = self.pay_data
csv_file = CSV_Manager.prepare_csv(#rows, ["Name", "Pay Period", "Gross Income", "Income Tax", "Net Income", "Superannuation"])
send_data csv_file, :type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment;filename=Payslip #{Date.today.to_s}.csv"
rescue
redirect_to root_url, notice: "CSV not supplied or invalid format"
end
end
When I run rspec spec/ I get below error:
Failure/Error: post '/payslips/process_csv', :csv => csv_file, :header => 1
ActionController::UrlGeneratorError:
No route matches...
What could be wrong in here that is causing this error?
params[:files][:headers] where you are passing :header => 1. Key is different. This will not cause no route found probably but just for correction. As per rails convention action doesn't has parameters
If you are going to pass optional params in any methods: Please have a look at : http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_methods.html
Following is the example of method defination:
def foo(arg1="Miles", arg2="Coltrane", arg3="Roach")
"#{arg1}, #{arg2}, #{arg3}."
end
Try this:
post :process_csv, :files => {:csv => csv_file, :header => 1}

Rspec 2.10.1, Rails 3.2.13 - ActionController::RoutingError: No route matches

I'm writing an rspec test that sends a JSON via POST to a member route end point. But I'm getting a "no route matches" error when I do so. I'm not sure if there's something I need to add because this endpoint is a member route, or I'm just missing some HTTP request headers because I'm sending a JSON. Please help.
This is what I have:
Spec:
describe "#endpoint" do
context "type 1" do
before(:each) do
post :create, #params.merge(:abc => {:first_user_id => #user1.id, :second_user_id => #user2.id})
#mashup = assigns(:mashup)
end
it "should post the results successfully" do
units = [...]
users = [...]
params = #params.merge(:mashup_outcome => {:status => "success", :assetName => "MashupAssetName", :winningUserId => #user1.id}, :mashup_id => #mashup.id, :version_number => 1, :user_id => #user1.id, :id => #mashup.id ,:users => :users).to_json
#request.env["CONTENT_TYPE"] = "application/json"
#had to have a param key for my params below in order to bypass the NoMethodError
#In actual request body, it's just a JSON
post :over, :mashup => params
#mashups.in_progress.should be_false
end
end
context "type 2" do
before(:each) do
...
end
it "should post the results correctly" do
...
end
end
Routes:
namespace :mashup do
resources :mashups do
member do
post :endpoint
end
end
Controller:
def endpoint
if #mashup.complete_mashup(params)
render :json => api_success(#mashup.dpoints)
else
render :json => api_error({})
end
end
Error:
Failure/Error: post :endpoint, :mashup => params
ActionController::RoutingError:
No route matches {:mashup => "{...<JSON>...}", :controller => "api/mashup/mashups", :action => "endpoint"}

rails render_to_string problem

I`m trying to test my controller with rspec and always get an error.
users_controller.rb:
def update
#user.update_attributes!(params[:user])
redirect_to #user, :status => 202, :text => render_to_string(:partial => "users/show", :type => "json", :locals => {:user => #user})
#notice, that redirect_to was reinitialized and :text is a parameter for response_body
end
_show.tokamak
user {
id user.id
email user.email
username user.username
}
spec file
it "should NOT update user username" do
username = #user.username
put 'update', :id => #user.id, :user => {:username => username+"abc"}, :format => :json
response.status.should be(202)
response.headers["Location"].length.should be > 0
puts response.body
#user.reload
#user.username.should eq(username)
end
end
So I get an error:
Failure/Error: put 'update', :id =>
#user.id, :user => {:username =>
username+"abc"}, :format => :json
ActionView::Template::Error:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
# C:/Users/makaroni4/free_frog/ffapi/app/views/users/_show.tokamak:1:in
_app_views_users__show_tokamak___509498818
_32151168_368311673'
# C:/Users/makaroni4/XXX/XXX/app/controllers/users_controller.rb:22:in
update'
# ./users_controller_spec.rb:34:in
`block (4 levels) in '
So may be I call render_to_string method wrong?
Try stubbing out find?
mock_user = User.stub(:find).with(#user.id) {#user}
To be honest I'd go a few steps further and make sure you mock and stub most of the relevant behavior of the User object (or whatever class #user is). Keep in mind you're only testing that the controller action returns what you expect if you give it valid input--not that the model itself does the right thing.
I had a lot of difficulty wrapping my head around the differences in model vs. controller specs...
I hope this helps...if not, I apologize in advance...
EDIT:
I'll take this a step futher and suggest this test is actually a model test. The actual controller test would be something like as the way your spec test should behave:
it "should NOT update user with invalid input" do
mock_user = mock_model(User, {}).as_null_object
User.stub(:find).with("12") {mock_user}
User.stub(:update_attributes).with({}).and_return(false)
put 'update', :id => "12"
# test that your output is correct, or even if the render target is what you expect.
end

RSPEC how to post to a controller? What's wrong with this?

I'm trying to post to my controller in RSPEC, see anything wrong with this? It's failing w/o error:
it "should store create an IncomingMail record" do
lambda {
post 'create', {
"from" => 'XXX',
"to" => 'XXX',
"cc" => 'XXX',
"subject" => 'XXX',
"message_text" => 'XXX',
"message_html" => 'XXX' }
}.should change { IncomingMail.count }.by(1)
end
Updated:
it "should store create an IncomingMail record" do
post :create,
:from => 'xx',
:to => 'xx',
:cc => 'xx',
:subject => 'xx',
:message_text => 'xx',
:message_html => 'xx'
mail = IncomingMail.last(:order => 'created_at desc')
mail.from.should == 'xx'
end
Controller
class IncomingMailsController < ApplicationController
require 'iconv'
#make sure that rails doesn't raise an exception because we have no way of knowing the token
skip_before_filter :verify_authenticity_token
def create
begin
#incoming_mail = IncomingMail.create(
:from => params[:from],
:to => params[:to],
:cc => params[:cc],
:subject => params[:subject],
:message_text => message_text_utf8,
:message_html => message_html_utf8
)
.....
This is how i do it :
Route Example :
post 'train_ability/:ability' => :train_ability, :as => 'train_ability'
Spec :
it "should increase the strength ability by one point and also update the strength_points by one if strength is the trained ability" do
#user.str = 10
#user.str_points = 0
#user.save!
post :train_ability, :ability => 'str'
#user.reload
flash[:error].should be_nil
#user.str_points.should == 1
#user.str.should == 11
end

Resources