RSPEC how to post to a controller? What's wrong with this? - ruby-on-rails

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

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.

trying to do a query session for Parse

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.

Strange expectation errors with RSpec

I've tested my controller and have got strange errors like this:
expected: ("376")
got: (376)
Please stub a default value first if message might be received with other args as well.
This is my spec:
it 'should send confirm-email if information is good' do
sign_in user
allow(Order).to receive(:find).with(order.id.to_s).and_return(order)
allow(order).to receive(:finalize) {order}
allow(order.errors).to receive(:empty?) {true}
expect(OrderMailer).to receive_message_chain(:send_finish_notification, :deliver)
patch :save_order, {:id => order.id , :order => {:street_address => 'Baker street', :apt => '123#', :zip_id => zip.id, :frequency_id => frequency.id, :amount_per_hour => '5',
:extras_ids => '', :phone_number => '3213', :credit_card_number => '4242424242424242', :credit_card_cvv => '777',
:credit_card_expiration => '12/20', :source_information => ''}}
end
And I've got this error in some logically close specs. But some tests passes, like this one:
it 'should not update user data if order errors is not empty' do
sign_in user
allow(Order).to receive(:find).with(order.id.to_s).and_return(order)
allow(order).to receive(:finalize) {order}
allow(order.errors).to receive(:empty?) {false}
expect(User).to_not receive(:update_user_data)
patch :save_order, {:id => order.id, :order => {:street_address => 'Baker street', :apt => '123#', :zip_id => zip.id, :frequency_id => frequency.id, :amount_per_hour => '5',
:extras_ids => '', :phone_number => '3213', :credit_card_number => '4242424242424242', :credit_card_cvv => '777',
:credit_card_expiration => '12/20', :source_information => ''}}
end
to_s or to_i doesn't help. The error line in controller -
#order = Order.find(params[:id]
So what could be in that case ? 'Cause it looks like some specs passes, but similar to them don't. Any suggestions ?

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 3 > Rendering views in rake task

I'm stuck with a rake task that need to prepare a newsletter for Mailchimp.
Using rails 2.x stuff googled I now have this code:
desc "Sends newsletter to Mailchimp list"
task :send_newsletter => :environment do
begin
# get render helpers
av = ActionView::Base.new(Rails::Application::Configuration.new(Rails.root).view_path)
av.class_eval do
include ApplicationHelper
end
things = Stuff.do.things
h = Hominid::Base.new({:api_key => "xxx"})
h.create_campaign(
{
:list_id => "xxx",
:subject => "Hey...",
:from_email => "xxx",
:from_name => "xxx",
:to_email => "",
:auto_footer => true,
:generate_text => true
},
{
:html => av.render(:template => "stuff/newsletter", :locals => {:things => things}, :layout => false)
},
"regular")
rescue Exception => e
STDERR.puts ">>> #{e.to_yaml}"
end
And I get this error message: "undefined method `virtual_path' for false:FalseClass"
My first try was with render_to_string but I just can't access as it is in the controller not the view.
Any help would be greatly appreciated :)
:layout => nil ?

Resources