我有一个spec/controllers/add_to_carts_spec.rb
:
require 'spec_helper'
describe CartItemsController do
before (:each) do
@user = Factory(:user)
sign_in @user
end
describe "add stuff to the cart" do
it "should add a product to the cart" do
product = FactoryGirl.create(:product)
visit products_path(product)
save_and_open_page
click_on('cart_item_submit')
end
end
end
和/spec/support/spec_helper.rb
:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.mock_with :rspec
config.use_transactional_fixtures = true
end
…也加载/spec/support/devise.rb
:
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
end
Guard在后台运行,并不断抛出这个:
Failures:
1) CartItemsController add stuff to the cart should add a product to the cart
Failure/Error: sign_in @user
NoMethodError:
undefined method `sign_in' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x1057fd428>
# ./spec/controllers/add_to_carts_spec.rb:7
我花了几个小时尝试各种配置调整和不同的语法,但似乎没有什么改变。什么好主意吗?
(编辑以反映较新的错误)
理想的解决方案是在spec/support/design创建一个文件。通过以下代码在Rspec配置中包含设计测试帮助器:
Rspec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
end
type参数只在控制器规范中包含helper,这是为了避免将来在测试模型或视图时调用它可能产生的问题。它是可选的。
我们决定添加一个独立的文件来包含helper,而不是像solnic那样将它们包含在规范中,原因是在规范重新生成的情况下,规范将被覆盖。
由于某些原因,这也不适合我,所以我只是在我的规格中手动包含这个助手,像这样:
describe CartItemsController do
include Devise::TestHelpers
# ...
end
这些测试助手不能用于集成/请求规范。在这些情况下测试设计的推荐方法是访问登录页面,填写表单并提交,然后运行测试。
请参阅David Chelimsky对之前关于这个主题的问题的回答,以获得更完整的解释。