【问题标题】:FactoryGirl,Rspec2 and devise rails 3FactoryGirl、Rspec2 和设计 rails 3
【发布时间】:2012-11-15 09:01:24
【问题描述】:

我正在使用 Rspec、FactoryGirl 和 Spork 进行测试。有两件事我不太清楚,首先是我的 factory.rb 文件的位置。目前我有它位于

spec/support/factories.rb

它看起来像这样

 FactoryGirl.define do
 factory :user do
 email                 "example@yahoo.com"
 password              "password"
 password_confirmation "password"
 confirmed_at           Time.now

 end 
 end

在我的 spec_helper 中有

config.include FactoryGirl::Syntax::Methods

其次,我想在开始对控制器进行测试之前登录用户,这个特定的控制器有一个前置过滤器:authenticate_user!

我正在使用设计进行身份验证,因此添加了

config.include Devise::TestHelpers, :type => :controller

阅读设计文档,您可以添加一个 controller_macros.rb 并指定这样的方法来使用

 def login_user
 before(:each) do
  @request.env["devise.mapping"] = Devise.mappings[:user]
  user = FactoryGirl.create(:user)
  user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are      using the confirmable module
  sign_in user
  end
  end

所以我也将它添加到我的 spec_helper 中

config.include ControllerMacros, :type => :controller

所以当我在控制器测试之前添加 login_user 时,我得到未定义的方法 login_user。我在这里使用两个工具来做同样的事情吗?我真的需要设计方法还是可以用 factoryGirl 完成。如果是这样,我如何在测试控制器之前设置登录过程?

【问题讨论】:

    标签: ruby-on-rails-3 rspec devise tdd factory-bot


    【解决方案1】:

    工厂地址应位于spec/factories。查看此示例应用程序https://github.com/RailsApps/rails3-devise-rspec-cucumber/tree/master/spec

    对于登录,通常您似乎做对了。在此处再次检查示例应用程序:https://github.com/plataformatec/devise/wiki/How-To:-Controllers-and-Views-tests-with-Rails-3-%28and-rspec%29

    对于undefined method login_user的错误一定要有

    Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
    

    config.extend ControllerMacros, :type => :controller
    

    在 spec_helper 中。设计方法应与主题可用:

    subject.current_user.should_not be_nil
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      • 2011-10-21
      相关资源
      最近更新 更多