2017-02-20 63 views
1

我是Rspec的新手,但是我已經成功地完成了一項工作(至少在我目前的測試中)的設置,可以讓我測試各種行爲在使用FactoryGirl + Devise和Warden助手登錄/註銷狀態。的流動遵循這些基本步驟:如何使用Rspec + Devise + FactoryGirl簽署用戶進出測試

  1. 廠女孩定義了一個通用用戶
  2. 每個測試塊需要一個登錄使用前(:每個)鉤在
  3. rails_helper登錄用戶配置扯下用戶登錄每次測試後用一個後:每個鉤子

我已經看了很多代碼示例來得到這個工作,但我還沒有找到一個完整的往返,雖然我知道這是在我的設置工作,我想知道這是否是正確的方式,具體而言,我是否在重複任何不合適的事情一如既往(就像用戶簽署拆除)或創造未來的意外行爲。

下面是每個步驟和測試樣品相關的代碼:

規格/ factories.rb

FactoryGirl.define do 

    factory :user do 
    sequence(:name)  { |n| "person #{n}"} 
    sequence(:email)  { |n| "person#{n}@example.com" } 
    password    'foobar' 
    password_confirmation 'foobar' 
    confirmed_at   Time.now 
    sequence(:id)   { |n| n } 
    end 
end 

規格/ rails_helper.rb

... 
    # Add login/logout helpers from Devise 
    config.include Devise::Test::ControllerHelpers, type: :controller 
    config.include Devise::Test::ControllerHelpers, type: :view 

    # Include Warden test helpers specifically for login/logout 
    config.include Warden::Test::Helpers 

    # Add capybara DSL 
    config.include Capybara::DSL 

    # Tear down signed in user after each test 
    config.after :each do 
    Warden.test_reset! 
    end 

規格/視圖/ static_pages (樣品測試)

RSpec.describe 'static_pages home, signed in', type: :view do 
    before(:each) do 
    @user = build(:user) 
    login_as(@user) 
    end 

    it 'should display the correct links when signed in' do 

    visit root_path 

    # links which persist in both states 
    expect(page).to have_link('Site Title', href: root_path, count: 1) 

    # links which drop out after login 
    expect(page).not_to have_link('Login', href: new_user_session_path) 
    expect(page).not_to have_link('Join', href: signup_path) 

    # links which are added after login 
    expect(page).to have_link('Add Item', href: new_item_path) 
    expect(page).to have_link('My Items', href: myitems_path) 
    end 
end 
+2

你看起來不錯。我不確定在您的情況下「往返」是什麼意思。 FWIW,請查看[RSPec功能測試](https://www.relishapp.com/rspec/rspec-rails/docs/feature-specs/feature-spec)。它是您看起來正在做的一般事情的支持機制,即功能級別測試。 –

+0

這是一個很好的提示,謝謝:) – oneWorkingHeadphone

回答

2

您的設置完全正常。 @Greg Tarsa說的一件事就是您可能想要在功能級別執行這樣的測試。我的另一件事是,應該使用一個單一的規格來測試一個單一的東西,例如它應該是單個(或多個)expectit塊。但這不是嚴格的規定 - 這取決於你自己決定。

我用前面的提示和功能樣式語法對你的設置進行了一些重構。也許這將是有用的:

background do 
    @user = build(:user) 
    login_as(@user) 
    visit root_path 
    end 

    scenario "links persist in both states" do 
    expect(page).to have_link('Site Title', href: root_path, count: 1) 
    end 

    scenario "links dropped out after login" do 
    expect(page).not_to have_link('Login', href: new_user_session_path) 
    expect(page).not_to have_link('Join', href: signup_path) 
    end 

    scenario "links added after login" do 
    expect(page).to have_link('Add Item', href: new_item_path) 
    expect(page).to have_link('My Items', href: myitems_path) 
    end 
+0

非常有幫助,並感謝您的重構! – oneWorkingHeadphone