1

私は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>

アプリはうまく機能します。失敗するのはテストだけです。どんな助けでも大歓迎です。ありがとう!

4

2 に答える 2

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 に貼り付けます。それはうまくいきました。ご協力いただきありがとうございます!

于 2013-05-01T00:13:28.550 に答える
0

sign_in_as はどこだ! 定義された? ApplicationController で定義されているため、テストでは使用できないようです。

おそらく、次のようなユーザーにログインするための統合テストがすでにあるでしょう。

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

その場合は、ほとんどのコードをヘルパー メソッドに引き出して、それを before ブロックで使用できるはずです。

編集: おそらく Devise を使用していることがわかりました。その場合は、spec_helper.rb を次のように編集する必要があります。

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

sign_in_as の代わりに sign_in を使用してください!

于 2013-04-30T01:09:08.163 に答える