我有一个 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
在过去的几个小时里,我尝试了各种配置调整和不同的语法,但似乎没有任何改变。有任何想法吗?
(编辑以反射(reflect)较新的错误)
最佳答案
理想的解决方案是在 spec/support/devise.rb 创建一个文件,并通过以下代码在 Rspec 配置中包含设计测试助手:
Rspec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
end
type 参数仅在您的 Controller 规范中包含帮助程序,这是为了避免将来在测试模型或 View 时调用它时可能出现的问题。它是可选的。
我们决定添加一个单独的文件来包含帮助程序,而不是像上面的 solnic 那样将它们包含在规范中的原因是,如果规范重新生成,规范将被覆盖。
关于ruby-on-rails-3 - 未定义方法 `sign_in' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x1057fd428> 尝试使用 Devise 设置 RSpec 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7141763/