Ruby on rails 设计;用户“已登录”;rspec中的方法

Ruby on rails 设计;用户“已登录”;rspec中的方法,ruby-on-rails,rspec,devise,rspec-rails,Ruby On Rails,Rspec,Devise,Rspec Rails,我有一个控制器操作,它使用Deviate的“用户登录?”作为条件。操作如下所示: def show if user_signed_in? #do stuff end end 但是当我在RSpec中测试这个动作时,测试失败了,因为if块中的代码从未执行过。是否有任何方法来存根“用户登录”方法?“由于用户可能未登录,因此代码不会执行。 要在rspec中登录设备用户,请在spec/support/controller\u macros.rb中登录 mo

我有一个控制器操作,它使用Deviate的“用户登录?”作为条件。操作如下所示:

 def show           
   if user_signed_in?
     #do stuff
   end
 end

但是当我在RSpec中测试这个动作时,测试失败了,因为if块中的代码从未执行过。是否有任何方法来存根“用户登录”方法?

由于用户可能未登录,因此代码不会执行。 要在rspec中登录设备用户,请在
spec/support/controller\u macros.rb中登录

module ControllerMacros
    def login_user
      before(:each) do
        @request.env["devise.mapping"] = Devise.mappings[:user]
        user = FactoryGirl.create(:user)
        user.confirm! #if you are using the "confirmable" module
        sign_in user
      end
    end
end
spec/rails\u helper.rb
中:

RSpec.configure do |config|
  config.include Devise::Test::ControllerHelpers, :type => :controller
  config.extend ControllerMacros, :type => :controller
end
然后在控制器规范中:

describe MyController do 
  login_user
  ....
end

代码未执行,因为用户可能未登录。 要在rspec中登录设备用户,请在
spec/support/controller\u macros.rb中登录

module ControllerMacros
    def login_user
      before(:each) do
        @request.env["devise.mapping"] = Devise.mappings[:user]
        user = FactoryGirl.create(:user)
        user.confirm! #if you are using the "confirmable" module
        sign_in user
      end
    end
end
spec/rails\u helper.rb
中:

RSpec.configure do |config|
  config.include Devise::Test::ControllerHelpers, :type => :controller
  config.extend ControllerMacros, :type => :controller
end
然后在控制器规范中:

describe MyController do 
  login_user
  ....
end

您可以像这样模拟
用户\u登录?
方法:

 def show           
   if user_signed_in?
     #do stuff
   end
 end
在做之前
允许(designe::Controllers::Helpers.)的任何实例接收(:user\u signed\u in?)并返回(false)
结束

您可以像这样模拟
用户登录?
方法:

 def show           
   if user_signed_in?
     #do stuff
   end
 end
在做之前
允许(designe::Controllers::Helpers.)的任何实例接收(:user\u signed\u in?)并返回(false)
结束

否,我已让用户登录。您显示的代码已存在于my app.Oops中。看来我忘了跳过前过滤器。他们是造成问题的人。对不起,我是新手。无论如何,谢谢。这给了我一个
method\u missing':未定义的方法,用于RSpec::ExampleGroups::PagesController:Class(NoMethodError),来自/home/klaus/.rvm/gems/ruby-2.2。2@rails-4-2-7/gems/designe-4.2.0/lib/designe/test/controller\u helpers.rb:28:在使用RSpec 3.5和designe 4.2.0的“阻塞”中,我已让用户登录。您显示的代码已存在于my app.Oops中。看来我忘了跳过前过滤器。他们是造成问题的人。对不起,我是新手。无论如何,谢谢。这给了我一个
method\u missing':未定义的方法,用于RSpec::ExampleGroups::PagesController:Class(NoMethodError),来自/home/klaus/.rvm/gems/ruby-2.2。2@rails-4-2-7/gems/designe-4.2.0/lib/designe/test/controller_helpers.rb:28:使用RSpec 3.5和designe 4.2.0在“块入”中