How to assign variables when using RSpec to test jbuilder views - json

I am trying to write RSpec tests to test the templates I have constructed using jbuilder which ultimately serves up JSON data for my API. I have many tests in spec/controllers which test my controller functionality, but I am looking to also test that I am rendering the correct JSON fields in my jbuilder views. Here is an example of what I have setup:
# app/views/api/v1/users/create.json.jbuilder
json.first_name user.first_name
# spec/views/api/v1/users/create.json.jbuilder_spec.rb
require 'spec_helper'
describe "api/v1/users/create.json.jbuilder" do
it "renders first_name" do
assign( :user, User.create( :first_name => "Bob" ) )
render
hash = JSON.parse( rendered )
hash.has_json_node( :first_name ).with( "Bob" )
end
end
What I get when I run rspec spec/views/api/v1/users/create.json.jbuilder_spec.rb is the following error
Failures:
1) api/v1/users/create.json.jbuilder render a user
Failure/Error: render
ActionView::Template::Error:
undefined local variable or method `user' for #<#<Class:0x007fa2911c3118>:0x007fa29105f2b8>
# ./app/views/api/v1/users/create.json.jbuilder:1:in `_app_views_api_v__users_create_json_jbuilder___3806288263594986646_70168098229960'
# ./spec/views/api/v1/users/create.json.jbulder_spec.rb:6:in `block (2 levels) in <top (required)>'
No matter how I have tried to assign/create/pass a user object to the template, it fails. Any idea what I might be doing wrong?

After much reading and iteration, this is what works:
require 'spec_helper'
describe "api/v1/users/create.json.jbuilder" do
let( :user ) { User.create( :not_strict => true ) }
it "renders first_name" do
render :template => "api/v1/users/create", :locals => { :user => user }, :formats => :json, :handler => :jbuilder
rendered.should have_json_node( :first_name ).with( user.first_name )
end
end
note: the have_json_node comes from the api_matchers gem.

assigns method sets instance variables, your view should be #user.first_name instead of user.first_name, or is that a partial? if it's a partial you should do render :partial => ..., if it's a template you should use #user

Related

Inject local variables into rails partial

I want my partial below to get the classy class from it being injected through locals, but I keep getting undefined method for classy.
//view
<%= render layout: "layouts/partial", locals: {className: "classy"} do %>
...
<% end>
//partial
<div class="regular-div <%=className if className?%>"></div>
To check if a local variable is set use local_assigns.has_key?(:some_key) or local_assigns[:some_key] to safely access the local variable.
A nifty way of handling the common task of building a list of classes is:
module ApplicationHelper
# Takes an array or list of classes and returns a string
# Example:
# class_list('a', 'b', nil, 'c')
# => "a b"
# class_list(['a', 'b', nil, 'c'])
# => "a b c"
def class_list(*classes)
[*classes].flatten.compact.join(' ')
end
end
Then you can do:
<div class="<%= class_list('regular-div', local_assigns[:className]) %>"></div>

Rails not passing the DB Query on search form

Here what looks better, this is the log, its passing the param, but its not passing a query with that param
Started GET "/items?utf8=%E2%9C%93&search=blanca" for 65.34.251.106 at 2016-08-30 03:55:51 +0000
Processing by ItemsController#index as HTML
Parameters: {"utf8"=>"✓", "search"=>"blanca"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 3]]
Item Load (0.3ms) SELECT "items".* FROM "items" LIMIT 50 OFFSET 0
Item Load (0.2ms) SELECT "items".* FROM "items" ORDER BY "items"."id" ASC LIMIT 1 OFFSET 0
Rendered items/_items.html.erb (3.2ms)
Rendered items/index.html.erb within layouts/application (4.9ms)
This is the controller:
def index
#items = Item.search(params[:search])
end
and this is the model:
class Item < ActiveRecord::Base
has_many :stocks
attr_accessible :nombre, :espesor, :material, :quantity
accepts_nested_attributes_for :stocks
attr_accessible :stocks_attributes
self.per_page = 50
# def self.search(search)
# Item.where("nombre LIKE ?", "%#{search}%")
# end
def self.search(search_term)
where("nombre LIKE ?", "%#{search_term}%")
end
protected
end
and the search form in the view:
<%= form_tag items_path, :method => 'get', :id => "items_search" do %>
<p>
<%= text_field_tag :search, params[:search], class: "form-control" %>
<%= submit_tag "Search", :name => nil, class: "btn btn-danger" %>
</p>
<div id="items"><%= render 'items' %>
</div>
<% end %>
I have a _items.html.erb file which has the items to render, that part works because no matter my input on the search bar, it always shows all the items
This is the ouput when i try to use .search method in the console
2.3.0 :041 > Item.search("blanca")
NoMethodError: undefined method `search' for #<Class:0x0000000203fc58>
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord- 4.2.6/lib/active_record/dynamic_matchers.rb:26:in `method_missing'
from (irb):41
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:110:in `start'
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:9:in `start'
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:68:in `console'
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
Are you sure you defined the class method search in item.rb? Cause the error says that there's no search method defined on the Item class. However, try if the following works for you.
You only want to search if the form is being submitted. You can use the present? method to know if the search term was actually passed.
Modify your controller to
def index
#items = params[:search].present? ? Item.search(params[:search]) : Item.all
end
Note that an object is present only if its not blank. This is handy because if someone enters " " in the form, you shouldn't search for an empty space in the nombre field but display all the records in the items table.
If the form was not submitted, Item.all will be executed.
Modify your class method to
def self.search(search_term)
where("nombre LIKE ?", "%#{search_term}%")
end
You don't need a Item.where because the class Item is the current context on which the where method is called. Note that I have changed the pattern to %#{search_term}% cause you don't always want to match strings ending with some pattern.
Hope this helps!

Ignore modules from Model

I have in my application a few controllers that i want to use as a api. In this api i need to use versioning.
in my routes.rb i`m using this:
require 'api_constraints'
(...)
scope '/:target/:version', :module => :api, :constraints => { :version => /[0-z\.]+/ } , :defaults => { :format => 'json' } do
scope :module => :v1, :constraints => ApiConstraints.new(:version => 1, :default => true) do
match '/list' => 'sample#list'
end
end
my api_constraints.rb:
class ApiConstraints
def initialize(options)
#version = options[:version]
#default = options[:default]
end
def matches?(req)
#default || req.headers['Accept'].include?("application/waytaxi.api.v#{#version}")
end
def self.version
#version
end
end
in my SampleController.rb:
module Api
module V1
class SampleController < ApiBaseController
def list
render json: Model.find_by_id(params[:id])
end
end
end
end
the ApiBaseController:
module Api
class ApiBaseController < ApplicationController
before_filter :authenticate
skip_before_filter :verify_authenticity_token
private
def authenticate
# if params[:target] == "ios"
# render :json => {status: 404}
# return false
# end
end
end
end
the problem is:
whenever i try to call Model i get this error:
uninitialized constant Api::V1::SampleController::Model
If i use: ::Model i get this error:
uninitialized constant Model
And yes, i do have this models on my database. If i use Model.all outside the SampleController i get the objects.
P.S.: I'm using rails 3.2.8
Found my problem.
My Model was in plural and on my controller i was calling it in singular

Import CSV Data in a Rails App with ActiveAdmin

i want to upload CSV files through the activeadmin panel.
on the index page from the resource "product" i want a button next to the "new product" button with "import csv file".
i dont know where to start.
in the documentation is something about collection_action, but with the code below i have no link at the top.
ActiveAdmin.register Post do
collection_action :import_csv, :method => :post do
# Do some CSV importing work here...
redirect_to :action => :index, :notice => "CSV imported successfully!"
end
end
anyone here who use activeadmin and can import csv data?
Continuing from Thomas Watsons great start to the answer which helped me get my bearings before figuring the rest of it out.
The code blow allows not just CSV upload for the example Posts model but for any subsequent models thereafter. all you need to do is copy the action_item ands both collection_actions from the example into any other ActiveAdmin.register block and the functionality will be the same. hope this helps.
app/admin/posts.rb
ActiveAdmin.register Post do
action_item :only => :index do
link_to 'Upload CSV', :action => 'upload_csv'
end
collection_action :upload_csv do
render "admin/csv/upload_csv"
end
collection_action :import_csv, :method => :post do
CsvDb.convert_save("post", params[:dump][:file])
redirect_to :action => :index, :notice => "CSV imported successfully!"
end
end
app/models/csv_db.rb
require 'csv'
class CsvDb
class << self
def convert_save(model_name, csv_data)
csv_file = csv_data.read
CSV.parse(csv_file) do |row|
target_model = model_name.classify.constantize
new_object = target_model.new
column_iterator = -1
target_model.column_names.each do |key|
column_iterator += 1
unless key == "ID"
value = row[column_iterator]
new_object.send "#{key}=", value
end
end
new_object.save
end
end
end
end
note: this example does a check to see whether or not the first column is an ID column, it then skips that column as rails will assign an ID to the new object (see example CSV below for reference)
app/views/admin/csv/upload_csv.html.haml
= form_for :dump, :url=>{:action=>"import_csv"}, :html => { :multipart => true } do |f|
%table
%tr
%td
%label{:for => "dump_file"}
Select a CSV File :
%td
= f.file_field :file
%tr
%td
= submit_tag 'Submit'
app/public/example.csv
"1","TITLE EXAMPLE","MESSAGE EXAMPLE","POSTED AT DATETIME"
"2","TITLE EXAMPLE","MESSAGE EXAMPLE","POSTED AT DATETIME"
"3","TITLE EXAMPLE","MESSAGE EXAMPLE","POSTED AT DATETIME"
"4","TITLE EXAMPLE","MESSAGE EXAMPLE","POSTED AT DATETIME"
"5","TITLE EXAMPLE","MESSAGE EXAMPLE","POSTED AT DATETIME"
note: quotations not always needed
Adding a collection_action does not automatically add a button linking to that action. To add a button at the top of the index screen you need to add the following code to your ActiveAdmin.register block:
action_item :only => :index do
link_to 'Upload CSV', :action => 'upload_csv'
end
But before calling the collection action you posted in your question, you first need the user to specify which file to upload. I would personally do this on another screen (i.e. creating two collection actions - one being a :get action, the other being your :post action). So the complete AA controller would look something like this:
ActiveAdmin.register Post do
action_item :only => :index do
link_to 'Upload posts', :action => 'upload_csv'
end
collection_action :upload_csv do
# The method defaults to :get
# By default Active Admin will look for a view file with the same
# name as the action, so you need to create your view at
# app/views/admin/posts/upload_csv.html.haml (or .erb if that's your weapon)
end
collection_action :import_csv, :method => :post do
# Do some CSV importing work here...
redirect_to :action => :index, :notice => "CSV imported successfully!"
end
end
#krhorst, I was trying to use your code, but unfortunately it sucks on big imports. It eat so much memory =( So I decided to use own solution based on activerecord-import gem
Here it is https://github.com/Fivell/active_admin_import
Features
Encoding handling
Support importing with ZIP file
Two step importing (see example2)
CSV options
Ability to prepend CSV headers automatically
Bulk import (activerecord-import)
Ability to customize template
Callbacks support
Support import from zip file
....
Based on ben.m's excellent answer above I replaced the csv_db.rb section suggested with this:
require 'csv'
class CsvDb
class << self
def convert_save(model_name, csv_data)
begin
target_model = model_name.classify.constantize
CSV.foreach(csv_data.path, :headers => true) do |row|
target_model.create(row.to_hash)
end
rescue Exception => e
Rails.logger.error e.message
Rails.logger.error e.backtrace.join("\n")
end
end
end
end
While not a complete answer I did not want my changes to pollute ben.m's answer in case I did something egregiously wrong.
expanding on ben.m's response which I found very useful.
I had issues with the CSV import logic (attributes not lining up and column iterator not functioning as required) and implemented a change which instead utilizes a per line loop and the model.create method. This allows you to import a .csv with the header line matching the attributes.
app/models/csv_db.rb
require 'csv'
class CsvDb
class << self
def convert_save(model_name, csv_data)
csv_file = csv_data.read
lines = CSV.parse(csv_file)
header = lines.shift
lines.each do |line|
attributes = Hash[header.zip line]
target_model = model_name.classify.constantize
target_model.create(attributes)
end
end
end
end
So your imported CSV file can look like this (use to match up with model attributes):
importExample.csv
first_name,last_name,attribute1,attribute2
john,citizen,value1,value2
For large excel which takes time on normal process, I created a gem that process Excel sheets using an active job and display results using action cable(websockets)
https://github.com/shivgarg5676/active_admin_excel_upload
Some of the solutions above worked pretty well. I ran into challenges in practice that I solved here below. The solved problems are:
Importing CSV data with columns in different orders
Preventing errors caused by hidden characters in Excel CSVs
Resetting the database primary_key so that the application can continue to add records after the import
Note: I took out the ID filter so I could change IDs for what I'm working on, but most use cases probably want to keep it in.
require 'csv'
class CsvDb
class << self
def convert_save(model_name, csv_data)
csv_file = csv_data.read
csv_file.to_s.force_encoding("UTF-8")
csv_file.sub!("\xEF\xBB\xBF", '')
target_model = model_name.classify.constantize
headers = csv_file.split("\n")[0].split(",")
CSV.parse(csv_file, headers: true) do |row|
new_object = target_model.new
column_iterator = -1
headers.each do |key|
column_iterator += 1
value = row[column_iterator]
new_object.send "#{key.chomp}=", value
end
new_object.save
end
ActiveRecord::Base.connection.reset_pk_sequence!(model_name.pluralize)
end
end
end

Rails 3: How to return a big JSON document

I want to return about 90k items in a JSON document but I'm getting this error when I make the call:
Timeout::Error in ApisController#api_b
time's up!
Rails.root: /root/api_b
I am simply running "rails s" with the default rails server.
What's the way to make this work and return the document?
Thanks
#bs.each do |a|
puts "dentro do bs.each"
#final << { :Email => a['headers']['to'], :At => a['date'], :subject => a['headers']['subject'], :Type => a['headers']['status'], :Message_id => a['headers']['message_id'] }
end
Being #bs the BSON object from MongoDB. The timeout is in "#final << ..."
If you are experiencing timeouts from rails and it is possible to cache the data (e.g. the data changes infrequently), I would generate the response in the background using resque or delayed_job and than have Rails dump that to the client. Or if the data cannot be cached, use a lightweight Rack handler like Sinatra and Metal to generate the responses.
Edited to reflect sample data
I was able to run the following code in a Rails 3.0.9 instance against a high performance Mongo 1.8.4 instance. I was using Mongo 1.3.1, bson_ext 1.3.1, webrick 1.3.1 and Ruby 1.9.2p180 x64. It did not time out but it took some time to load. My sample Mongo DB has 100k records and contains no indexes.
before_filter :profile_start
after_filter :profile_end
def index
db = #conn['sample-dbs']
collection = db['email-test']
#final = []
#bs = collection.find({})
#bs.each do |a|
puts "dentro do bs.each"
#final << { :Email => a['headers']['to'], :At => a['date'], :subject => a['headers']['subject'], :Type => a['headers']['status'], :Message_id => a['headers']['message_id'] }
end
render :json => #final
end
private
def profile_start
RubyProf.start
end
def profile_end
RubyProf::FlatPrinter.new(RubyProf.stop).print
end
A more efficient way to dump out the records would be
#bs = collection.find({}, {:fields => ["headers", "date"]})
#final = #bs.map{|a| {:Email => a['headers']['to'], :At => a['date'], :subject => a['headers']['subject'], :Type => a['headers']['status'], :Message_id => a['headers']['message_id'] }}
render :json => #final
My data generator
100000.times do |i|
p i
#coll.insert({:date =>Time.now(),:headers => {"to"=>"me#foo.com", "subject"=>"meeeeeeeeee", "status" => "ffffffffffffffffff", "message_id" => "1234634673"}})
end