How to test Rspec For controller, - ruby-on-rails-3.1

How to Rectify this error in RSpec for Controller,
1) SellersController GET index find the Activity
Failure/Error: assigns(:activity).should eq([activity])
expected: [#<Activity id: 65, transactable_type: "admin", transactable_id: 1, action_type: "seller", user_id: 1, is_approved: false, approved_by: nil, created_at: "2012-04-09 11:02:17", updated_at: "2012-04-09 11:02:17", associatable_type: nil, associatable_id: nil>]
got: nil
(compared using ==)
Seller_rspec.rb
describe "GET index" do
it "find the Activity" do
activity = Activity.create!(:transactable_type=>"admin",:transactable_id=>1,:action_type=>"seller",:user_id =>1,:is_approved=>0)
get :index,{:is_approved => activity.to_param,:user_id=>1,:approved_by=>"admin"}
assigns(:activity).should eq([activity])
end
In controller
def index
#activities=Activity.find(:all,:select => 'DISTINCT transactable_type,transactable_id,action_type,is_approved,approved_by',:conditions=>["is_approved= ? and user_id=? and approved_by IS NULL",false,current_user.id])
end

You are putting a code into controller which should go to the model. Create a method or scope in Activity model like:
def self.find_not_approved(current_user_id)
find(:all,
:select => 'DISTINCT transactable_type,transactable_id,action_type,is_approved,approved_by',
:conditions= ["is_approved= ? and user_id=? and approved_by IS NULL",
false,
current_user_id])
end
So you can just have in controller (I've made up the method name):
def index
#activities = Activity.find_not_appoved(current_user.id)
end
And just to anser your question, it should be assigns(:activities).should eq([activity]) not assigns(:activity).should eq([activity]) - as your are checking #activities variable in controller not, #activity.

Related

rspec expect symbol not equal to created object

I wrote a test for controll with rspec:
it "populates an array of books" do
book = FactoryGirl.create(:book)
get :index
expect(:books).to eql([book])
end
books_controller.rb
def index
#books = Book.all.order("created_at DESC")
end
books.rb
FactoryGirl.define do
factory :book do |f|
f.name { Faker::Book.title }
f.author { Faker::Book.author }
f.press { Faker::Book.publisher }
f.cover { fixture_file_upload(Rails.root.join('spec', 'photos', 'testcover.jpg'), 'image/png') }
end
end
Run bin/rake spec, the result is:
1) BooksController GET #index populates an array of books
Failure/Error: expect(:books).to eql([book])
expected: [#<Book id: 1, name: "The Waste Land", author: "谢靖琪", isbn: nil, press: "University of Chicago Press"...e: "image/png", cover_file_size: 104531, cover_updated_at: "2016-08-26 04:00:19", page_number: nil>]
got: :books
(compared using eql?)
Diff:
## -1,2 +1,2 ##
-[#<Book id: 1, name: "The Waste Land", author: "谢靖琪", isbn: nil, press: "University of Chicago Press", description: nil, grade_level: nil, lexile_level: nil, douban_link: nil, scholastic_link: nil, created_at: "2016-08-26 04:00:19", updated_at: "2016-08-26 04:00:19", cover_file_name: "fcbcb7417dbc88827d16765a.jpg", cover_content_type: "image/png", cover_file_size: 104531, cover_updated_at: "2016-08-26 04:00:19", page_number: nil>]
+:books
They are not equal. It seems that the first expected result, '...' is an abbreviation. How can I fix it?
I think what you want is
expect(assigns(:books)).to eq([book])

How to access form object parameters in active admin

Really hope this is actually possible but I can't seem to access my forms parameters to send with my custom action
My aim here is for a user to fill in their form, click on a Preview button that will show them what their post will look like, i have created the view which is fine, just passing the parameters is an issue.
This is my current form
# Create Blog Post
form do |f|
inputs 'Blog' do
f.semantic_errors
f.input :title
f.input :category_id, as: :select, collection: Category.all
f.input :comments, as: :text, input_html: { rows: 10, cols: 10 }
f.input :published, as: :boolean
end
inputs 'Submit' do
f.actions do
f.action :submit
f.action :cancel
f.action :reset
li do
link_to 'Preview', preview_my_admin_panel_posts_path(post: { title: "test", comments: 'comments', category_id: '1' }) # Hardcoded for now
end
end
end
end
# Collection Action to handle object
collection_action :preview, method: :get do
#post = Post.new(permitted_params[:post])
end
So with everything the way it is (hardcoded) the params are passed through and output in my preview view, but as soon as i try accessing the forms object/params nothing gets passed th
# Console Output
1 - link_to 'Preview', preview_my_admin_panel_posts_path(post: { title: f.object.title, comments: f.object.comments, category_id: f.object.category_id})
#<Post:0x007f8bbe1fc4c0 id: nil, title: "", comments: "", category_id: nil, slug: nil, published: 0, created_at: nil, updated_at: nil>
2 - link_to 'Preview', preview_my_admin_panel_posts_path(post: { title: f.title, comments: f.comments, category_id: f.category_id })
# Console Output
#<Post:0x007f8bbe1fc4c0 id: nil, title: nil, comments: nil, category_id: nil, slug: nil, published: 0, created_at: nil, updated_at: nil>
3 - link_to 'Preview', preview_my_admin_panel_posts_path(#post)
# Console Output
#<Post:0x007f8bbe1fc4c0 id: nil, title: nil, comments: nil, category_id: nil, slug: nil, published: 0, created_at: nil, updated_at: nil>
Not sure where else to go with this, f.object.param seems close but passing through empty strings? has anyone done this before ?
If anyone has an alternative solution would love to hear it.
Thanks
Update
When outputting params to the console i get this returned
{"action"=>"preview", "controller"=>"my_admin_panel/posts"}
Are you trying to create a post? When you load this page the fields do not have any value thus the link will not load any parameter(you can inspect element on the preview link and see that the link does not have any parameter).
One way is to use JavaScript to catch the value before the link has routed in controller.

Alias attribute ruby ActiveResource::Base

class ChatMessage < ActiveResource::Base
alias_attribute :user_id, :userId
alias_attribute :chat_id, :chatId
alias_attribute :message_text, :MessageText
...
I Have the problem that what I return from an API has attribute names that I don't like, e.g. see camelCaps. I don't want to do this to every model in my application. Is there some method missing magic I could apply?
Cheers
Thomas
You can do a little of metaprogramming here:
module JavaAliasing
def initialize(hash)
super(Hash[hash.map do |k,v|
[k.to_s.gsub(/[a-z][A-Z]/) { |s| s.split('').join('_') }.downcase.to_sym, v]
end])
end
end
Let me illustrate this:
class Instantiator
def initialize(hash)
hash.each { |k,v| instance_variable_set "##{k}", v }
end
end
Instantiator.new(asdf: 2).instance_variable_get('#asdf') #=> 2
class MyARModel < Instantiator
include JavaAliasing
end
MyARModel.new(asdfQWER: 2).instance_variable_get("#asdf_qwer") #=> 2
Here, a real life example (rails 4.0):
> Player.send :include, JavaAliasing
> Player.new(name: 'pololo', username: 'asdf', 'teamId' => 23)
=> #<Player id: nil, name: "pololo", username: "asdf", email: nil, type: "Player", created_at: nil, updated_at: nil, provider: nil, uid: nil, team_id: 23, last_login: nil, last_activity: nil>

Mongoid: ActiveModel Numericality Validation, allow_nil does not work

I've defined a Mongoid model with an Integer field for which i validate numericality like this
# source.rb
class Source
field :code, type: Integer
validates_numericality_of :code, allow_nil: true
The purpose of allow_nil is to validate fields which are present & ignore nil values.
But here, allow_nil completely bypasses the numericality check
object = Source.new
object.code = "ABC"
object.valid?
=> true
object
=> #<Source _id: 50d00b2d81ee9eae46000001, _type: nil, code: 0>
In activerecord, this works correctly
object = Source.new
object.code = "ABC"
object.valid?
=> false
object
=> #<Source id: nil, code: 0, created_at: nil, updated_at: nil>
object.save
(0.1ms) begin transaction
(0.1ms) rollback transaction
=> false
Mongoid behaves slightly different to Active Record when using #valid? on already persisted data. Active Record's #valid? will run all validations whereas Mongoid's #valid? will only run validations on fields where data has changed as an optimization. - see mongoid validation
so this could be your problem.
you could try
validates_numericality_of :code, :allow_nil => true
and
validates :code, :numericality => true ,:allow_nil => true

Attribute Not Being Added to Object

I'm trying to add an attribute to a model object. Direct access works but when I print the entire object or encode it into JSON, that attribute is left out. Can someone tell me what I'm doing wrong?
Here is my rails console output:
irb(main):010:0> b=ChatMessage.new(:user_id=>4,:room_id=>1,:message=>"Hello World")
=> #<ChatMessage id: nil, room_id: 1, user_id: 4, message: "Hello World", created_at: nil, updated_at: nil>
irb(main):011:0> b.sender_nickname="bbb"
=> "bbb"
irb(main):012:0> b.sender_nickname
=> "bbb"
irb(main):013:0> b
=> #<ChatMessage id: nil, room_id: 1, user_id: 4, message: "Hello World", created_at: nil, updated_at: nil>
Here is my model code:
class ChatMessage < ActiveRecord::Base
attr_accessor :sender_nickname
def self.get_last_message_id
last_message=ChatMessage.all.last
last_message.nil? ? 0 : last_message.id
end
def self.get_all_messages_after(room_id,message_id)
ChatMessage.where("room_id = ? AND id > ?",room_id,message_id)
end
end
edit:
Here is the migration file for chat_messages table.
I'm not really looking to save sender_nickname. So it's more like a virtual attribute (but is still in db through association). And I might need to add other attributes later that aren't in the db. Is it possible to do it without using association?
def self.up
create_table :chat_messages do |t|
t.integer :room_id
t.integer :user_id
t.string :message
t.timestamps
end
end
as far as I know to_json will only take the attributes in the model and serialize (as in chat_message.attributes, not attr_accessor).
You properbly got a sender, or user model, or anything like that.
What I would do is to make a relation to the sender, user or what its called, with a belong_to, and then use this code to convert it to json:
chat_message.to_json(:include => { :sender => { :only => :nickname } })
It may also work with you code, and then just:
chat_message.to_json(:include => { :sender_nickname })
There also some documentation here: http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html
Hope it helps :)

Resources