问题描述
我当前正在创建一个使用OmniAuth来创建和验证用户的应用程序.由于Factory Girl无法在没有OmniAuth的情况下生成用户,因此在测试过程中遇到了问题.
I am currently creating an application that uses OmniAuth to create and authenticate users. I am encountering problems during testing due to Factory Girl being unable to generate users without OmniAuth.
我有几种不同的方法来让工厂女工使用omniauth创建用户,但没有一种成功.
I have several different ways to get factory girl to create users with omniauth but none have been successful.
我已将以下两行添加到我的spec_helper文件中
I have added the following 2 lines to my spec_helper file
OmniAuth.config.test_mode = true \\ allows me to fake signins
OmniAuth.config.add_mock(:twitter, { :uid => '12345', :info => { :nickname => 'Joe Blow' }})
当前的factory.rb
current factories.rb
FactoryGirl.define do
factory :user do
provider "twitter"
sequence(:uid) { |n| "#{n}" }
sequence(:name) { |n| "Person_#{n}" }
end
end
以下测试当前失败,因为没有生成用户
The following test currently fails because no user is being generated
let(:user) { FactoryGirl.create(:user) }
before { sign_in user }
describe "registering" do
it "should increment" do
expect do
click_button 'register'
end.to change(user.rounds, :count).by(1)
end
我应该如何更改我的工厂/测试,以便让Factory Girl使用OmniAuth创建测试用户?
How should I change my factories/tests in order to get Factory Girl to create test users with OmniAuth?
我使用了 RailsCast指南来设置Omniauth ,
#create function inside user.rb
def self.create_with_omniauth(auth)
create! do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.name = auth["info"]["name"]
end
end
希望也有用
#create inside the session_controller
def create
auth = request.env["omniauth.auth"]
user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
session[:user_id] = user.id
redirect_to root_url, :notice => "Signed in!"
end
推荐答案
您是否记得在测试设置中的某处进行了以下操作?
Did you remember to do the following somewhere in the test setup?
request.env ["omniauth.auth"] = OmniAuth.config.mock_auth [:twitter]
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter]
如果您这样做了,那么用户的UID是否可能与模拟uid不匹配?
If you did, is it possible the user's UID doesn't match the mock uid?
您可以尝试将工厂定义从sequence(:uid) { |n| "#{n}" }
更改为uid '12345'
.
You can try changing the factory definition from sequence(:uid) { |n| "#{n}" }
to uid '12345'
.
这篇关于使用OmniAuth在Factory Girl中创建用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!