how to fix "Rendered ActiveModel::Serializer::Null with Hash" - active-model-serializers

I am trying to write API for user model, where i have to return only two columns with some modification(appending string)
Every thing work's fine, I even get the correct result, but when I see status code its showing '500', when i check the logs its showed the following error
[active_model_serializers] Rendered ActiveModel::Serializer::Null with Hash
following is the code
1. users_controller.rb
class Api::V1::UsersController < Api::V1::ApiController
# GET
def pl_details
render json: {pl: current_user.pl_url, enabled: current_user.personal_calendar_enabled}, status: :success
end
...
end
user.rb
...
def pl_url
return "#{Rails.application.secrets.app_host}/#{self.calendar_url_token}"
end
...
user_serializer.rb
class UserSerializer < ActiveModel::Serializer
attributes :id, :firstname, :lastname, :email
end

Never mind,
I just did it other way around,I used a separate Serializer to avoid the error, following is the approach
class Api::V1::UsersController < Api::V1::ApiController
# GET
def pl_details
render json: current_user,serializer: PLSerializer, status: :success
end
...
end
and inside PLSerializer
class PLSerializer < ActiveModel::Serializer
attributes :pl, :personal_calendar_enabled
def personal_link
current_user.pl_url
end
end

Related

How to write unit_test for a function which only updates a global dict type variable - Python(pytest)

Unit-Test code for a function which does a validation operation and updates the Global dict - result_count = {'test_method':{'Total_tested': 0, 'passed': 0, 'failed': 0}
below is the function
def validate_response(testmethod, response, expected_data):
ra = response.json()
expected = expected_data['payload']
if (response.status_code == expected['response_status']) \
and (result_count[testmethod['folder']]["FAILED"] < 10):
------code logic - checks using jsondiff and re.expressions--
else:
missmatch = 'response status code missmatch'
update_result(testmethod, 'status_code', expected_data, response, missmatch, fail=True)
result_count[testmethod['folder']]['FAILED'] += 1
Need to write test for the above function. to check if the result_count is updated properly.
Regular expression library & jsondiff is also used in the mentioned function.
help required for mocking the global variable and using the same for testing.
During executing the test script below i was getting a key error for the global variable result_count. That implies that the code is unable to access the result_count.. the key error after the update - is throwing TypeError: '<=' not supported between instances of 'MagicMock' and 'int' as Error
The current issue is that the result_count is not updated when the below line code is executed.
partner_test.validate_response(test_input_mocker.method, response, expected_data)
my unit test script is as below
#patch("tests.p_test.result")
#patch("tests.p_test.result_count")
def test_validate_response_pass(result_count_mocker, monkeypatch, result_mocker, test_input_mocker):
# Build data for validate response function
response = Resp(200, {'message': 'pong'})
response_data = response.json()
expected_data = {some_test_data}
# global variable import and initialize result, result_count
from p_test import result, result_count
result_count.update(result_count_mocker.data)
result.update(result_mocker.data)
result_count_mocker.return_value = result_count_mocker.data
def update_result_mocker(*args):
mock operations here
return None
monkeypatch.setattr(partner_test, "update_result", update_result_mocker)
p_test.validate_response(test_input_mocker.method, response, expected_data)
Resp() in the test fnction is a response class created to mock the response object.
the issue can be resolved using #patch.dict(dict_name, values) below is the solution
#patch.dict(p_test.result, {dict_values })
#patch.dict(p_test.result_count, {dict_values})
def test_validate_response(monkeypatch, test_input_mocker, result_count_test):
response = Resp(200, {'message': 'pong'})
response_data = response.json()
expected_data = {----your data-----}
def update_result_mocker(*args):
# mock_operations
monkeypatch.setattr(p_test, "update_result", update_result_mocker)
p_test.validate_response(test_input_mocker.method, response, expected_data)
print(p_test.result_count)

how to stub a method that takes and argument

I'm kind of stuck (Maybe because this is my first time using Minitest) wherein I want to stub a method that takes an argument.
def self.bonsai_site_configuration(since=nil)
data = []
Site.all.reduce(data) do |data, site|
begin
data << JSON.parse(site.bonsai_desc)
rescue StandardError => exception
notify_exception(exception)
end
data
end
return {data: data`}
end
All I'm looking over here is that if test cases wherein if the site.bonsai_desc fails(i.e throw an exception). It should invoke notify_exception with given exception
Here how my minitest looks like
test "should return bonsai_site_configuration even on exception" do
site = Site.first
raises_exception = -> { raise 'boom' }
Site.stub(:all, [site]) do
site.stub(:bonsai_desc, raises_exception) do
Site.stub(:notify_exception) do
bonsai_information = Site.bonsai_site_configuration
assert_equal(0, bonsai_information[:data].count)
end
end
end
end
Upon running the minitest the test passes but I want to ensure that argument check is also included.
What am I suppose to do?

Rails 4 activeadmin - undefined local variable or method `view_factory' for :Arbre::Context

i am using activeadmin gem for my admin interface,now i created a new controller and added layout 'acitveadmin'
am getting the below error
NameError in MeetingRooms#index
Showing /home/amp/.rvm/gems/ruby-2.1.1#rails4.1/bundler/gems/active_admin-41d5176f3682/app/views/layouts/active_admin.html.arb
where line #2 raised:
undefined local variable or method `view_factory' for :Arbre::Context
my controller is
app/controllers/meeting_rooms_controller.rb
class MeetingRoomsController < ApplicationController
layout 'active_admin'
def index
#meeting_rooms = MeetingRoom.all
#render :layout => "active_admin"
end
end
can any one please help me.
I think you should use the controller block to define actions.
https://github.com/activeadmin/activeadmin/blob/master/docs/8-custom-actions.md#modifying-the-controller
ActiveAdmin.register MeetingRoom do
controller do
# This code is evaluated within the controller class
def define_a_method
# Instance method
end
end
end
In the controller block you can use the feature of the InheritedResources.
https://github.com/josevalim/inherited_resources#overwriting-actions

page-object gem seems not working

I am trying to use page-object gem in my watir-webdriver scripts and I think I might be missing something.
Here is my code for log_in.rb:
require "./all_deals"
class LogIn
include PageObject
text_field(:email, :id => 'UserName')
text_field(:password, :id => 'Password')
checkbox(:remember_me, :id => 'RememberMe')
button(:log_me_in, :value => 'Login')
def initialize(browser)
#browser = browser
end
def log_in (email, password)
self.email = email
self.password = password
remember_me
log_me_in
AllDeals.new(#browser)
end
end
My home_page.rb
require "./log_in"
class HomePage
def initialize(browser)
#browser = browser
end
def visit
#browser.goto "http://treatme.co.nz/"
end
def go_to_log_in
#browser.goto "https://treatme.co.nz/Account/LogOn"
LogIn.new(#browser)
end
end
Here is my log_in_test.rb
require "rubygems"
require "test/unit"
require "watir-webdriver"
require "page-object"
require "./home_page"
class LogInTest < Test::Unit::TestCase
def setup
#browser ||= Watir::Browser.new :firefox
end
def teardown
#browser.close
end
def test_fail
#home_page = HomePage.new(#browser)
#home_page.visit
#log_in_page = #home_page.go_to_log_in
#all_deals = #log_in_page.log_in("test#gmail.com","test")
assert (#all_deals.get_title == "GrabOne Daily Deals - Buy Together, Save Together")
end
end
The result of the test run is:
Finished tests in 22.469286s, 0.0445 tests/s, 0.0000 assertions/s.
1) Error:
test_fail(LogInTest):
NoMethodError: undefined method `text_field_value_set' for nil:NilClass
C:/Ruby193/lib/ruby/gems/1.9.1/gems/page-object-0.9.2/lib/page-object/accessors.rb:142:in `block in text_field'
I am using Ruby 1.9 with page-object gem 0.9.2.
Can you please help me?
Also in each of those rb file, I need to require the class files it references, is there a way I don't have to declare it every time?
Thanks so much.
Addressing the Exception
That exception is occurring do to the LogIn page re-defining the initialize method.
class LogIn
include PageObject
def initialize(browser)
#browser = browser
end
end
When you include PageObject, it already adds a specific initialization method. Your class is overriding that initialization and presumably causing something to not get setup correctly.
Removing the initialize method will get you past that exception.
However, you will then hit a remember_me is not a variable/method exception. Assuming you want to check the checkbox, it should be check_remember_me.
Requiring Class Files
I usually have my test file require a file that requires all my page_objects. It is a similar concept to how your would require any other gem or library.
For example, I would create a treatme.rb file with:
require 'log_in'
require 'home_page'
Assuming you require the files in the required order (ie files that are needed by others are required first), none of your page object files (ie log_in.rb and home_page.rb) should need to do any requiring.
Your test files would then just require your treatme.rb file. Example:
require './treatme'

Rails 4: Correct way to create objects from other model from the controller

Using strong_params from Rails 4, what is the preferred best way to do this?
I used the below solution but are uncertain if this is the best way to do it. ( it works though )
Example:
game_controller.rb ( shortcut version!)
# inside game controller we want to build an Participant object
# using .require fails, using .permits goes true
def GameController < ApplicationController
def join_game_as_participant
#participant = Participant.new(participant_params)
end
end
def participant_params
params.permit(:participant,
:participant_id,
:user_id,
:confirmed).merge(:user_id => current_user.id,
:game_id => params[:game_id])
end
Your participant_params method should be private and you should use the require method :
private
def participant_params
params.require(:participant).permit(
:participant_id, :user_id, :confirmed
).merge(
:user_id => current_user.id, :game_id => params[:game_id]
)
end
Hope this help

Resources