NoMethodError:未定义的方法`sign_in_as!',FactoryGirl,Rspec,Rails

时间:2013-04-30 00:47:08

标签: ruby-on-rails rspec factory-bot

我是Rails的新手。我使用FactoryGirl为我的集成测试创建用户,我无法弄清楚如何在测试中登录我的用户。

我的工厂看起来像这样:

FactoryGirl.define do
    factory :user do
        sequence(:email) { |n| "user#{n}@ticketee.com" }
        password "password"
        password_confirmation "password"
    end

    factory :confirmed_user do
        after_create { |user| user.confirm! }
    end
end

我的测试看起来像这样:

feature 'Editing an exercise' do

    before do
        ex = FactoryGirl.create(:ex)
        user = FactoryGirl.create(:user)
        user.confirm!
        sign_in_as!(user)
    end

    scenario 'can edit an exercise' do
        visit '/'
        click_link 'Exercises'
        click_link 'running'
        click_link 'edit'
        fill_in 'Name', :with => 'kick boxing'
        fill_in 'Description', :with => 'kicking a box'
        click_button 'Save'
        page.should have_content('Exercise updated!')
        page.should have_content('kick boxing')
    end
end

当我运行测试时,我收到错误:

Failure/Error: sign_in_as!(user)
NoMethodError:
undefined method `sign_in_as!' 
for #<RSpec::Core::ExampleGroup::Nested_1:0xb515ecc>

该应用程序运行良好,它只是失败的测试。任何帮助,将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

你是对的,我的测试找不到sign_in_as !,我最后写了一个看起来像这样的身份验证助手:

module AuthenticationHelpers
    def sign_in_as!(user)
        visit '/users/sign_in'
        fill_in "Email", :with => user.email
        fill_in "Password", :with => "password"
        click_button "Sign in"
        page.should have_content("Signed in successfully.")
    end
end

RSpec.configure do |c|
    c.include AuthenticationHelpers, :type => :request
end

并将其粘贴在spec / support / authentication_helpers.rb中。那很有效。 谢谢你的帮助!

答案 1 :(得分:0)

sign_in_as在哪里!界定?在我看来,它在ApplicationController中定义,因此在测试中不可用。

您可能已经有一个集成测试来登录您的用户,如下所示:

scenario "user logs in" do
  visit '/'
  fill_in "Username", with: "username"
  ...
end

如果是这种情况,您应该能够将大部分代码提取到辅助方法中并在之前的块中使用

编辑: 我刚才发现你可能正在使用Devise,在这种情况下你应该像这样编辑你的spec_helper.rb:

RSpec.configure do |c|
  ...
  c.include Devise::TestHelpers
  ...
end

并使用sign_in代替sign_in_as!

相关问题