jeudi 2 juillet 2015

Why rails minitest testcases are failing

My posts_controller_Test.rb file:

# test/controllers/posts_controller_test.rb
require 'test_helper'

class PostControllerTest < ActionController::TestCase
    def setup
       @post = Post.new
    end

    test 'should get index' do
        get :index
        assert_response :success
        assert_not_nil assigns(:posts)
    end
end

My post_controller File

class PostsController < ActionController::Base
    before_action :authenticate_user!

    def index
        @post = current_user.posts.paginate(page: params[:page], per_page: 5)
        respond_to do |format|
            format.html
            format.json { render json: @post }
        end
    end

    def new
        @post = Post.new
    end

    def create
        @post = current_user.posts.build(post_param)
        if @post.save
            redirect_to action: 'index'
        else
            render 'new'
    end
end

Why my test cases are failing? Is it because I have authenticate_user! condition? I also have .yml file and tried to test with it but after initializing with .yml data I am getting RuntimeError: @controller is nil: make sure you set it in your test's setup method.

yml file

one:
 data 2
 value: 3
 user_id: 1
 name: 'test'

.yml has everything what i have required in

params.require(:post).permit(:data, :value, :name) and obvious `user` for foreign key reference

Edit -1

After the suggestion of inheriting with ApplicationController

Got this new error:

 NameError: uninitialized constant ApplicationController::Base

Rake task can't load ActionMailer records from Rails.cache "ArgumentError: undefined class/module ApplicationMailer"

I want to generate an email list that deliver the emails later using the whenever gem and rake tasks.

namespace :email_reminder do
  task create_user_list: :environment do
    redis_hash = {}
    User.where(XXX).each do |user|
      items_to_remind = Item.where(XXX)
      redis_hash[user.id] = items_to_remind
    end
    redis_hash["updated_at"] = Time.now
    $redis.set "saved_email_list", redis_hash.to_json
  end

  task create_email_array: :environment do
    data = JSON.parse($redis.get("saved_email_list"))
    email_array = []
    data.each do |k,v|
        ### Access records user, items array ###
        email_array << ApplicationMailer::items_reminder(user, items)
    end
    Rails.cache.write("items_reminder_emails", email_array)
  end

  task deliver_emails: :environment do
    Rails.cache.read("items_reminder_emails").map { |e| e.deliver }
  end
end

Everything works find except I get an error in the last rake task when trying to access the Rails.cache. If I run the same code in rails console there is not problem.

rake aborted!
ArgumentError: undefined class/module ApplicationMailer

Additional Question: Is there a better way to do this? Can I store the AppMailer records in Redis?

How to use 'ANY' in where clause with Rails 4.0 instead of 'IN'?

I used to have a query like :

MyModel.where(id: ids)

Which generates sql query like:

SELECT  "my_models".* FROM "my_models"  WHERE "my_models"."id" IN (1, 28, 7, 8, 12)

Now I want to change this to use ANY instead of IN

I created this:

MyModel.where("id = ANY(VALUES(#{ids.join '),('}))"

Now when I use empty array ids = [] I get the foloowing error:

  MyModel Load (53.0ms)  SELECT "my_models".* FROM "my_models"  WHERE (id = ANY(VALUES()))
ActiveRecord::JDBCError: org.postgresql.util.PSQLException: ERROR: syntax error at or near ")"
ActiveRecord::StatementInvalid: ActiveRecord::JDBCError: org.postgresql.util.PSQLException: ERROR: syntax error at or near ")"
  Position: 75: SELECT "social_messages".* FROM "social_messages"  WHERE (id = ANY(VALUES()))
    from arjdbc/jdbc/RubyJdbcConnection.java:838:in `execute_query'

Javascript Alert in Rails app - checkbox for params hash

I'm working on a Rails app that's using an external api for authentication. If the the same login credentials are used simultaneously the app has to alert the second user that there's already a session in progress. This needs to be a JavaScript alert with an 'ok' box, and the return has to be passed to the api as a flag to kill the first session.

I've got ideas for parts of it, but it's not coming together.

A hidden input in the login form that's triggered by the alert box?

I also tried this for the alert, but I'm unsure of how to pass 'msg' into the JavaScript, and this doesn't even address the params issue.

login_controller.rb

  elsif body['ValidationMessage'] == 'OtherSessionActive'
    flash[:alert] = auth_config['session_alert']
    redirect_to login_path and return
  else

login.html.erb

  <div id='flash'>
    <% flash.each do |name, msg| %>
        <% if name == :alert %>
            <script>
                alert(#{msg})
            </script>
        <% else %>
            <%= content_tag :div, msg, :id => "flash_#{name}" %>
        <% end %>
    <% end %>
  </div>

Any ideas would be appreciated.

Ruby on rails make public/assets hidden unless logged in

I have a ruby on rails application that has sensitive images in assets/templates that after precompilation are moved to public/assets.

I need to make these directories hidden unless a user is logged in.

rake test returns NoMethodError: undefined method `[]' for nil:NilClass

First off we have an empty database.yml, all configurations are in application.yml using Figaro gem.

My team is in the process of upgrading to rails 4.0.0 from rails 3.2.0

when running guard or rake test, I get the following error.

rake aborted!
NoMethodError: undefined method `[]' for nil:NilClass

Tasks: TOP => minitest:run => test:prepare => db:test:load => db:test:purge
(See full trace by running task with --trace)

I added this to our Application controller => Figaro.load

Now I can run guard but rake test still fails with the same error.

Thanks for your help.

Query the database with Rails where method with optional parameters

I have index action that get parameters from url like http://localhost:3000/api/budgets?marketplace_id=1&budget_year_id=3&vendor=pepsi&details=sugarfree and use them to query the database with where method. But there are two parameters that are mandatory( marketplace_id and budget_year_id) and two more that are optional (vendor and details).For mandatory parameters i can just do Budget.where("marketplace_id=? and budget_year_id=?",params[:marketplace_id], params[:budget_year_id]) .My question is how would i query for optional parameters since they are might not always be there? Here is index action

def index
   unless params[:marketplace_id].blank? || params[:budget_year_id].blank?
      @budgets = Budget.where("marketplace_id=? and budget_year_id=?",params[:marketplace_id], params[:budget_year_id])# How do i add optional parameters ,vendor and/or details
      respond_with (@budgets)
   else
      render :json=>{:errors =>"Marketplace_id and Budget_year_id must be present",:status=>402}
   end
end