使用RSpec和Factory Girl测试Devise

4

编辑 请阅读我对这个问题的评论

我很新手rails,请多多包涵。 我一直在尝试使用factory girl和rspec配置Devise的测试。这花了我最好的2个小时,搜索了一半的互联网也没有结果。尽管有很多关于我的问题的线程,但我就是想不出来。

这是我的/spec文件的样子。

GET Home Gives the correct status code
     Failure/Error: sign_in user
     NoMethodError:
       undefined method `sign_in' for #<RSpec::Core::ExampleGroup::Nested_2:0x00000106f32558>
     # ./spec/models/user_spec.rb:6:in `block (2 levels) in <top (required)>

这是我在尝试进行以下测试时收到的错误信息:

user_spec.rb:

require 'spec_helper'

describe "GET Home" do
  before do

##I have tried all sorts of things here. I have also tried to define a module in devise.rb (see note below*), and then call that module here instead of the 2 lines below. But I get the same error, no local variable or undefined method for ...

    user = FactoryGirl.create(:user)
    sign_in user
  end

  describe "GET /Home"
  it "Gives the correct status code" do
    get root_path
    response.status.should be(200)
  end


end

在spec/factories/users.rb文件中:

FactoryGirl.define do 
    factory :user do 
        name "Christoffer"
        email "test@test2.com" 
        password "testtest" 
        password_confirmation "testtest" 
    end 
end

以下内容包含在spec_helpers.rb文件中。
config.include FactoryGirl::Syntax::Methods
config.include Devise::TestHelpers, :type => :controller

现在,通过这样做,我得到了上面的错误。有人能解释一下我做错了什么吗?可能是很明显的问题,因为我对Rails的方式并不是很熟悉。


*注意(我试图在devise.rb中定义并插入before do模块):

module ValidUserRequestHelper
    # Define a method which signs in as a valid user.
    def sign_in_as_a_valid_user_nommels
        # ASk factory girl to generate a valid user for us.
        @user ||= FactoryGirl.create :user

        # We action the login request using the parameters before we begin.
        # The login requests will match these to the user we just created in the factory, and authenticate us.
        post_via_redirect user_session_path, 'user[email]' => @user.email, 'user[password]' => @user.password
    end
end

原来我试图在spec/models中完成这个任务,而不是在spec/controllers中。现在我想知道,'spec/requests'文件夹的目的是什么? - Chris
1个回答

0

'spec/requests' 的目的是进行集成测试。您可以从用户角度测试应用程序的功能(例如,填写某些信息,然后单击按钮,然后如果某些输入有效或无效,则会发生这样那样的事情)。 spec/models 和 spec/controllers 通常用于单元测试,其中您测试应用程序的较小部分(例如,如果传递给用户模型的密码和password_confirmation参数不匹配会发生什么)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接