尝试使用Devise设置RSpec时,未定义的方法`sign_in'用于#<rspec :: core :: examplegroup :: nested_1 :: nested_1:0x1057fd428>错误</rspec :: core :: examplegroup :: nested_1 :: nested_1:0x1057fd428 >

时间:2011-08-21 23:11:10

标签: ruby-on-rails-3 rspec rspec2 rspec-rails

我有一个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

我花了最近几个小时尝试各种配置调整和不同的语法,但似乎没有任何改变。有什么想法吗?

(编辑以反映更新的错误)

3 个答案:

答案 0 :(得分:18)

理想的解决方案是在spec / support / devise.rb创建一个文件,并通过以下代码在Rspec配置中包含设计测试助手:

Rspec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end

type参数仅包含控制器规范中的帮助程序,这是为了避免在测试模型或视图时调用时可能出现的未来问题。这是可选的。

我们决定添加一个离散文件以包含帮助程序的原因,而不是像上面的solnic那样将它们包含在规范中,因为如果规范被重新生成,那么规范将被覆盖。

答案 1 :(得分:14)

出于某种原因,这对我来说也不起作用,所以我只是在我的规范中手动包含这个帮助:

describe CartItemsController do
  include Devise::TestHelpers

  # ...
end

答案 2 :(得分:12)

这些测试助手不适用于集成/请求规范。在这些情况下测试Devise的推荐方法是访问登录页面,填写表单并提交,然后运行测试。

有关此主题的问题,请参阅David Chelimsky's answer以前的SO问题,以获得更完整的解释。