我使用Rspec的,FactoryGirl和水豚。 当使用的ActiveSupport :: TimeZone.us_zones。 我跑我的测试我的requests/users_spec
,它甚至不打测试,因为它在出厂时的问题。 以下是错误:
Failure/Error: make_user_and_login
ActiveRecord::RecordInvalid:
Validation failed: Time zone is not included in the list
# ./spec/support/user_macros.rb:3:in `make_user_and_login'
# ./spec/requests/users_spec.rb:7:in `block (3 levels) in <top (required)>'
这是我的设置:
应用程序/模型/ user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :remember_me, :username, :time_zone
validates_presence_of :username
validates_presence_of :time_zone
validates_format_of :username, :with => /^(?=(.*[a-zA-Z]){3})[a-zA-Z0-9]+$/
validates_uniqueness_of :email
validates_uniqueness_of :username, :case_sensitive => false
validates_length_of :username, :within => 3..26
validates_inclusion_of :time_zone, :in => ActiveSupport::TimeZone.us_zones
end
投机/ spec_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'capybara/rspec'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
config.include(MailerMacros)
config.include(UserMacros)
end
投机/ factories.rb
FactoryGirl.define do
factory :user do
username 'user1'
time_zone '(GMT-05:00) Eastern Time (US & Canada)'
email 'user@example.com'
password 'testing'
end
end
规格/支持/ user_macros.rb
module UserMacros
def make_user_and_login
user = FactoryGirl.create(:user)
visit login_path
page.should have_selector('title', :text => 'Login')
fill_in('Email', :with => user.email)
fill_in('Password', :with => user.password)
click_button('Login')
page.should have_selector('title', :text => 'Home')
end
end
当我在我的一般用户模式运行测试通过了所有的测试。 为什么它不承认一个时区的时候真的是?
回答
在我User.rb模式,我不得不这样做:
validates_inclusion_of :time_zone, :in => ActiveSupport::TimeZone.us_zones.map(&:name)
我厂:
factory :user do
username 'user1'
email 'user@example.com'
time_zone 'Eastern Time (US & Canada)'
password 'testing'
end
我的看法:
<%= f.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones, {:prompt => "Select Your Time Zone *"} %>
如果你有从水豚测试请求:
page.select('(GMT-10:00) Hawaii', :from => 'Time Zone')
祝好运。