使用Devise + Rspec2 + Spork / Guard请求规范

时间:2013-02-28 19:46:48

标签: ruby-on-rails-3 integration-testing rspec2 guard spork

我已经设置了Rspec2 + Spork + Guard + Devise

我的文件如下

#spec_helper.rb
Spork.prefork do
  #code
  Dir[Rails.root.join('spec/support/**/*.rb')].each {|f| require f}
  RSpec.configure do |config|
    config.extend ControllerMacros, :type => :controller 
  end 
end

Spork.each_run do
  # This code will be run each time you run your specs.
  FactoryGirl.reload
  include ControllerMacros
end

#spec/support/controller_macros.rb
module ControllerMacros
    def login_user
      before(:each) do
        @request.env["devise.mapping"] = Devise.mapping[:user]
        user = FactoryGirl.create(:user)
        sign_in user
      end
    end
end

#spec/support/devise.rb
Spec.configure do |config|
    config.include Devise::TestHelpers, :type => :controller
end

在我的请求规范

#spec/features/documents_spec.rb
require 'spec_helper'

describe "Documents" do

  login_user

  describe "GET /documents" do
    it "should display document name as sameera CV" do
      #spec code
    end
  end
end

当我运行bundle exec guard时,我得到了

  1) Documents GET /documents should display document name as sameera CV
     Failure/Error: Unable to find matching line from backtrace
     NoMethodError:
       undefined method `env' for nil:NilClass
     # ./spec/support/controller_macros.rb:4:in `block in login_user'

到目前为止,我已经通过谷歌做了很多修复,似乎没有任何工作,有人可以帮助我:)

我在

  • rails 3.2.9
  • rspec 2.12.0
  • 设计2.2.3

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

尝试在@request.env["devise.mapping"] = Devise.mapping[:user]

中将request.env["devise.mapping"] = Devise.mapping[:user]更改为spec/support/controller_macros.rb

答案 1 :(得分:0)

我在回答自己的问题,并且能够找到问题的解决方法。

以下是我做的步骤

1)从支持目录

中删除了controller_macros.rbdevise.rb

2)从ControllerMacros

中删除了spec_helper.rb个引用

3)将以下代码添加到

#spec/features/documents_spec.rb
before(:each) do
   user = FactoryGirl.create(:user)
   visit root_path
   fill_in 'user_email', :with => user.email
   fill_in 'user_password', :with => user.password
   click_button 'Sign in'
end

我确信应该有一种更优雅的方式(如设计维基中所述),但这可以:)