Check if an object is an ActiveRecord scope
Don't say is_a?(ActiveRecord::NamedScope::Scope)
because that is no longer true in Rails 3 and also doesn't match unscoped ActiveRecord classes themselves (which we consider scopes for all practical purposes).
A good way is to say this instead:
object.respond_to?(:scoped)
Related cards:
JavaScript: How to check if an object is NaN
JavaScript's NaN
("Not a Number") is hard to compare against. It never equals anything, not even itself:
NaN === NaN; // false
Number.NaN === NaN; // false
There is the isNaN
method, but it is not really what you are looking f...
Rails: How to check if a certain validation failed
If validations failed for a record, and you want to find out if a specific validation failed, you can leverage ActiveModel's error objects.
You rarely need this in application code (you usually just want to print error messages), but it can be u...
Rails and Postgres: How to test if your index is used as expected
This is a small example on how you can check if your Postgres index can be used by a specific query in you Rails application. For more complex execution plans it might still be a good idea to use the same path of proof.
1. Identify the...
How to check if a file is a human readable text file
Ruby's File class has a handy method binary?
which checks whether a file is a binary file. This method might be telling the truth most of the time. But sometimes it doesn't, and that's what causes pain. The method is defined as follows:
RSpec matcher to check if an ActiveRecord exists in the database
The attached RSpec matcher exist_in_database
checks if a given record still exists in the database and has not been destroyed:
describe Ticket do
describe '.purge_expired' do
fresh_ticket = Ticket.create(:expiry => Date.tomorrow)
...
Testing if two date ranges overlap in Ruby or Rails
A check if two date or time ranges A and B overlap needs to cover a lot of cases:
- A partially overlaps B
- A surrounds B
- B surrounds A
- A occurs entirely after B
- B occurs entirely after A
This means you actually have to check that:
...
RSpec: be_true does not actually check if a value is true
Don't use be_true
to check if a value is true
. It actually checks if it anything other than nil
or false
. That's why it has been renamed to be_truthy
in recent RSpec versions.
Th...
Check if two arrays contain the same elements in Ruby, RSpec or Test::Unit
RSpec 1, RSpec 2
To test whether two arrays have the same elements regardless of order, RSpec 1 and 2 give you the =~
matcher:
actual_array.should =~ expected_array
Rspec 3
With RSpec 3's expect
s...
Check if a field or button is disabled with Cucumber
Using this step definition you can check if any form field (text field, checkbox, etc) or button is disabled:
Then the "Name" field should be disabled
And the "Save" button should be disabled
But the "Locked" field should not be dis...