2016-01-21 86 views
0

我需要测试一个只有在用户使用Devise登录后才能使用的系统。每次使用“它”时,我都必须包含注册码。如何计算Capybara rspec测试代码?

有没有办法将以下代码考虑进去,以便"let's me make a new post"测试和类似测试不必包含注册?

describe "new post process" do 
    before :all do 
    @user = FactoryGirl.create(:user) 
    @post = FactoryGirl.create(:post) 
    end 

    it "signs me in" do 
    visit '/users/sign_in' 
    within(".new_user") do 
     fill_in 'Email', :with => '[email protected]' 
     fill_in 'Password', :with => 'password' 
    end 
    click_button 'Log in' 
    expect(page).to have_content 'Signed in successfully' 
    end 

    it "let's me make a new post" do 
    visit '/users/sign_in' 
    within(".new_user") do 
     fill_in 'Email', :with => '[email protected]' 
     fill_in 'Password', :with => 'password' 
    end 
    click_button 'Log in' 

    visit '/posts/new' 
    expect(find(:css, 'select#post_id').value).to eq('1') 
    end 

end 
+0

https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara – Jon

+0

你想“让我做一个新的职位”测试不运行注册,对吧? – fabersky

+0

@fabersky我希望它记住之前注册过的用户,这样我就不必在每次测试时都包含该代码 – Tom

回答

0

你的第一选择是使用所提供的Warden方法,按照文件在此页上:

https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara

你的第二个选择是刚登录真正在你的测试,你有在你的例子中完成。通过创建一些辅助方法来完成登录工作,而不是在所有测试中重复代码,您可以简化此操作。

为此,我将在您的spec目录中创建一个support目录,然后在该目录中创建一个macros目录。然后创建一个文件spec/support/macros/authentication_macros.rb

module AuthenticationMacros 
    def login_as(user) 
    visit '/users/sign_in' 
    within('.new_user') do 
     fill_in 'Email', with: user.email 
     fill_in 'Password', with: user.password 
    end 
    click_button 'Log in' 
    end 
end 

接下来,更新您的RSpec config来加载宏。在这两种spec_helper.rbrails_helper.rb如果您使用的是较新的设置:

# Load your support files 
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } 

# Include the functions defined in your modules so RSpec can access them 
RSpec.configure do |config| 
    config.include(AuthenticationMacros) 
end 

最后,更新你的测试使用您的login_as功能:

describe "new post process" do 
    before :each do 
    @user = FactoryGirl.create(:user) 
    @post = FactoryGirl.create(:post) 

    login_as @user 
    end 

    it "signs me in" do 
    expect(page).to have_content 'Signed in successfully' 
    end 

    it "let's me make a new post" do 
    expect(find(:css, 'select#post_id').value).to eq('1') 
    end 
end 

显然,要确保你有password在用户定义的厂。

相关问题