2017-02-20 68 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