2014-03-31 53 views
4

編輯閱讀我的評論對這個問題測試設計使用RSpec與工廠女孩

我很新的軌道,所以請多多包涵。 我一直在嘗試使用工廠女孩和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 

in spec/factories/users.rb:

FactoryGirl.define do 
    factory :user do 
     name "Christoffer" 
     email "[email protected]" 
     password "testtest" 
     password_confirmation "testtest" 
    end 
end 

而且folling線包括在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 
+0

我原來是試圖在規格/型號中做到這一點,而不是規格/控制器。現在我還在想,'spec/requests'文件夾的用途是什麼? – Chris

回答

0

'的投機/請求' 的目的是爲了集成測試。您可以從用戶的角度測試應用程序的功能(即填寫特定信息,然後單擊按鈕,如果某些輸入有效或無效,那麼應該會發生這種情況)。規範/模型和規範/控制器通常用於單元測試,您可以在其中測試應用程序的較小部分(即如果傳遞給用戶模型的密碼和password_confirmation參數不匹配,會發生什麼情況)