【发布时间】:2014-09-26 23:52:26
【问题描述】:
我正在测试地址模型中城市属性条目的验证。我的型号规格如下
require 'rails_helper'
RSpec.describe Address, :type => :model do
before(:each) do
@valid_attributes = {
street: 'rock avenue',
city: 'MSA',
zip: '00100',
person_id: 1
} # runs before each it block
end
context "Validations" do
it 'must have a city' do
a = Address.new
expect(a.errors_on(:city)).not_to be_empty
end
end
end
当我运行规范时,我收到以下错误
1) Address Validations must have a city
Failure/Error: expect(a.errors_on(:city)).not_to be_empty
NoMethodError:
undefined method `errors_on' for #<Address:0xd844538>
# ./spec/models/address_spec.rb:19:in `block (3 levels) in <top (required)>'
我的测试 gem 在我的 Gemfile 中设置如下
group :development, :test do
gem 'rspec-rails'
gem 'factory_girl_rails', :require => false
end
group :test do
gem 'capybara'
gem 'guard'
gem 'guard-rspec'
gem 'libnotify'
gem 'rspec-collection_matchers'
end
我在我的 spec_helper 中包含了 rspec 集合匹配器,所以我不明白为什么会出现这个错误
我的 spec_helper.rb
require 'capybara/rspec'
require 'factory_girl_rails'
require 'rspec/collection_matchers'
但是我可以看到方法 errors_on 已在 rspec-collection_matchers gem 中定义,如here
我的.rspec
--color
--require spec_helper
我也换了位置
require 'rspec/collection_matchers'
到 rails_helper.rb,但再次运行测试套件会出现同样的错误
rails_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require 'rspec/collection_matchers'
require 'capybara/rspec'
require 'factory_girl_rails'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.include Capybara::DSL
config.include FactoryGirl::Syntax::Methods
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
end
我的 spec_helper.rb 是空的,只有下面的块:
RSpec.configure do |config|
end
我正在使用 Rails 4.1.0、rspec 3.0.0 和 rspec-collection_matchers 1.0.0
【问题讨论】:
-
您的规范需要
rails_helper,但您将require 'rspec/collection_matchers'行放入spec_helper-- 您的rails_helper文件是否需要'spec_helper'? -
@DylanMarkow 是的,我的 rails_helper.rb 文件需要 spec_helper
标签: ruby-on-rails rspec tdd