问题
I am using ActiveSupport::TimeZone to set the time zone on a location based on the zip code.
def set_time_zone
self.time_zone = ActiveSupport::TimeZone.find_by_zipcode(self.zip)
end
This works just fine in the application itself. I am calling the set_time_zone on before_save.
In running the tests with Rspec, when it tries to run the set_time_zone method it errors out with "undefined method 'find_by_zipcode'in ActiveSupport::TimeZone"
I have included "require 'active_support/time_with_zone'" in my spec helper as well.
For now my work around is excluding the before save if in test environment.
Any ideas would be great.
回答1:
find_by_zipcode
is not part of the main ActiveSupport::TimeZone
object. The docs for that object are here, and you won't find any mention of zip codes.
A Google search found that method as part of the TZip gem. Since you said it works in your application, I would guess that you have that gem there. You probably just need to add it to your test project. (Sorry, not familiar with Ruby or RSpec all that well, so can't guide you there).
Being quite familiar with time zones, I thought I would also take this opportunity to address a few concerns about the general idea of mapping zip codes to time zones. I'm not so sure that it is a great idea.
- It is very U.S. focused. Time Zones are worldwide, and zip codes only work in the USA.
- Zip codes change frequently. The USPS publishes databases that you can subscribe to for changes to this data. It would appear from the TZip commit history and issue tracker that they have been manually adding zip code mappings as problems are reported. This is not a good way to handle data that is frequently changing.
- A zip code is not the best boundary to identify a location. There are many zip codes that cover disparate, non-contiguous areas. There are also administrative zip codes that don't map to any particular location (like those for overseas military mail).
- For those databases that assign a latitude and longitude to a particular zip code, those coordinates are often artificially chosen, as an approximation of the centroid of the area serviced by that zip code. Again, this is not a discrete location.
- According to the TZip source code, there are only 7 time zones covered by these mappings. They have forgotten about US territories that also have zip codes, such as Guam. Others, like Puerto Rico have been erroneously mapped to the Eastern time zone instead of the Atlantic time zone.
So my recommendation would be to avoid this approach entirely. Instead, use one of the methods described in this community wiki.
来源:https://stackoverflow.com/questions/16347730/activesupporttimezone-not-recognized-in-rspec-tests