Rails 3 - Pass a parameter to custom validation method - ruby-on-rails-3

I am looking to pass a value to a custom validation. I have done the following as a test:
validate :print_out, :parameter1 => 'Hello'
With this:
def print_out (input="blank")
puts input
end
When creating an object or saving an object, the output is 'blank.' However, if called directly:
object.print_out "Test"
Test is instead outputted. The question is, why is my parameter not passing properly?

Inside the 'config\initializers\' directory, you can create your own validations. As an example, let's create a validation 'validates_obj_length.' Not a very useful validation, but an acceptable example:
Create the file 'obj_length_validator.rb' within the 'config\intializers\' directory.
ActiveRecord::Base.class_eval do
def self.validates_obj_length(*attr_names)
options = attr_names.extract_options!
validates_each(attr_names, options) do |record, attribute, value|
record.errors[attribute] << "Error: Length must be " + options[:length].to_s unless value.length == options[:length]
end
end
end
Once you have this, you can use the very clean:
validates_obj_length :content, :length => 5
Basically, we reopen ActiveRecord::Base class and implement a new sub-validation. We use the splat (*) operator to accept an array of arguments. We then extract out the hash of options into our 'options' variable. Finally we implement our validation(s). This allows the validation to be used with any model anytime and stay DRY!

You could try
validate do |object_name|
object_name.print_out "Hello"
end
Instead of your validate :print_out, :parameter1 => 'Hello'.

Related

Rspec: Stubbing out a where statement in a controller test

I'm writing the following test:
let!(:city_areas) { FactoryGirl.create_list(:city_area, 30) }
before {
#city_areas = mock_model(CityArea)
CityArea.should_receive(:where).and_return(city_areas)
}
it 'should assign the proper value to city areas variable' do
get :get_edit_and_update_vars
assigns(:city_areas).should eq(city_areas.order("name ASC"))
end
to test the following method:
def get_edit_and_update_vars
#city_areas = CityArea.where("city_id = '#{#bar.city_id}'").order("name ASC").all
end
However, it fails out, saying that there's no method 'city_id' for nil:NilClass, leading me to believe it's still attempting to use the instance variable #bar.
How do I properly stub out this where statement to prevent this?
Why are you doing #city_areas = mock_model(CityArea) and then you never use #city_areas again?
I would test it this way:
inside the model CityArea create a named scope for this: where("city_id = '#{#bar.city_id}'").order("name ASC")
then in your controller spec you do
describe 'GET get_edit_and_update_vars' do
before(:each) do
#areas = mock('areas')
end
it 'gets the areas' do
CityArea.should_receive(:your_scope).once.and_return(#areas)
get :get_edit_and_update_vars
end
it 'assign the proper value to city areas variable' do
CityArea.stub!(:your_scope => #areas)
get :get_edit_and_update_vars
assigns(:city_areas).should eq(ordered)
end
end
and you should also create a spec for that new scope on the model spec
just a tip, you shouldn't use should_receive(...) inside the before block, use stub! inside before and use should_receive when you want to test that method is called
also, you shouldn't need to use factorygirl when testing controllers, you should always mock the models, the model can be tested on the model spec

Number validation - reference to another attribute

I need a validation to check whether an attribute is less or equal than another (virtual) attribute of the same record. How can I do that?
Sample code (not working - NoMethodError):
attr_reader :virt
attr_accessible :virt
validates :my_attr, :numericality => {:only_integer => true, :less_or_equal => self.virt}
(please be gentle and explicit, I'm a RoR newb :])
Since those validation lines are going to be executed when the class definition is first encountered, self.virt doesn't exist.
You can usually pass in a lambda/proc instead that will be called at validation time from the scope of the object:
validates :my_attr, :numericality => { :less_or_equal => lambda { virt } }
This still isn't that great, though. A better route would be to just define your own validation method:
validate :my_attr_is_within_range
def my_attr_is_within_range
my_attr <= virtual_attribute
end
This is much cleaner and more explicit. Note that you don't need to use self here since there is no ambiguity (if you were setting you would need the self).

Rails, creating a callback

I want to use an ActiveModel callback to be called after an object has been voted on, the issue is that the gem I'm using (voteable_mongo) to make the model votable doesnt provide like a vote model or callback in my app, so how can I create a callback for it?
set_callback(:vote, :before) do |object|
object.do_something
end
Obviously that vote action I made up, but the gem I'm using has this method, how would you properly extend this method to trigger a callback?
Taking the plugin example as source here's what you could do:
class Post
include Mongoid::Document
include Mongo::Voteable
extend ActiveModel::Callbacks
define_model_callbacks :vote
# set points for each vote
voteable self, :up => +1, :down => -1
def vote(options, value = nil)
_run_vote_callbacks do
super( options, value )
end
end
end
I did not run this code so I am not sure if this is going to work correctly or not, but in the worst case you could alias the vote method using alias_method_chain or just copy and paste the source to inside the _run_vote_callbacks block (really, really ugly, but it's a solution anyway).
EDIT
This could also be done using alias_method_chain, if the code above does not work:
class Post
include Mongoid::Document
include Mongo::Voteable
extend ActiveModel::Callbacks
define_model_callbacks :vote
# set points for each vote
voteable self, :up => +1, :down => -1
alias_method_chain :vote, :callback
def vote_with_callback(options, value = nil)
_run_vote_callbacks do
vote_without_callbacks( options, value )
end
end
end

Want to return a global variable instead of a local variable

I am verifying the existence of "test_results" in the application controller. It is returned as a local variable. I would like to call it once and have it available for the whole session. How do i do that?
"test_results" in application controller:
def test_results
(0 .. 4).each do |x| # looks for answers to the first 4 questions
if #answers[x].nil? || #answers[x] == 0.0
return false
break
end
end
return true
end
other controllers:
before_filter :test_results
if test_results
...do stuff
else
...display "take the test"
end
error message from view:
undefined local variable or method `test_results'
You can try using #
if #instrument_results
Edit
The result of before filter isn't stored. I don't know what you want to do but you can set a controller level variable inside the test_results function and then referer it as #controller.variable_name. But if your intention is to make a conditional view based on test_results return value, I suggest you to make a redirect to another action in the test_results method and put the success content in the current controller.
You can use :only and :except modifier to check which action of the controller will call the :before_filter.
Hope this helps.

What am I doing wrong with this rspec helper test?

All I'm trying to do is spec how a one line helper method for a view should behave, but I'm not sure what kind of mock object, (if any) I should be creating if I'm working in Rails.
Here's the code for events_helper.rb:
module EventsHelper
def filter_check_button_path
params[:filter].blank? ? '/images/buttons/bt_search_for_events.gif' : '/images/buttons/bt_refine_this_search.gif'
end
end
And here's my spec code, in events_helper_spec.rb:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe EventsHelper do
#Delete this example and add some real ones or delete this file
it "should be included in the object returned by #helper" do
included_modules = (class << helper; self; end).send :included_modules
included_modules.should include(EventsHelper)
end
it "should return the 'refine image search' button if a search has been run" do
# mock up params hash
params = {}
params[:filter] = true
# create an instance of the class that should include EventsHelper by default, as the first test has verified (I think)
#event = Event.new
# call method to check output
#event.filter_check_button_path.should be('/images/buttons/bt_search_for_events.gif')
end
end
When I've looked through the docs here - http://rspec.info/rails/writing/views.html, I'm mystified as to where the 'template' object comes from.
I've also tried looking here, which I thought would point me in the right direction, but alas, no dice. http://jakescruggs.blogspot.com/2007/03/mockingstubbing-partials-and-helper.html
What am I doing wrong here?
Thanks,
Chris
You are not doing anything in that spec, just setting a stub, so it will pass, but hasn't tested anything.
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe EventsHelper do
it "should return the 'refine image search' button if a search has been run" do
# mock up params hash
params = {:filter => true}
helper.stub!(:params).and_return(params)
helper.filter_check_button_path.should eql('/images/buttons/bt_search_for_events.gif')
end
end
I'm running my test without spec_helper (Ruby 1.9)
require_relative '../../app/helpers/users_helper'
describe 'UsersHelper' do
include UsersHelper
...
end
Ah,
I asked this question on the rspec mailing list, and one kind soul (thanks Scott!) explained to me that there's a handy helper object for this, that you should use instead, like so:
Rails has its own helper function
params = {:filter => true}
helper.stub!(:params).and_return(params)
I've now updated the code like so:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe EventsHelper do
#Delete this example and add some real ones or delete this file
it "should be included in the object returned by #helper" do
included_modules = (class << helper; self; end).send :included_modules
included_modules.should include(EventsHelper)
end
it "should return the 'refine image search' button if a search has been run" do
# mock up params hash
params = {}
params[:filter] = true
helper.stub!(:filter_check_button_path).and_return('/images/buttons/bt_search_for_events.gif')
end
end
And it's working. Huzzah!