blog.sowatchasayin

Rails etc.

Showing posts with label factory_girl. Show all posts
Showing posts with label factory_girl. Show all posts

Fakerとfactory_girlで偽物大量生産

適当なデータを作るときのお供に。
factory_girlと組み合わせて便利でした。

これが

Factory.define :message do |f|
f.title Faker::Lorem.sentence
f.body Faker::Lorem.paragraph
end


こうなります!

>> y Factory.build :message
--- !ruby/object:Message
attributes:
created_at:
body: Quasi ab fuga reprehenderit quia. Nostrum laud...(以下略)
title: Alias dolor velit ut et vitae magnam aut non.
updated_at:
recipient_id:
sender_id:

適当なデータが入ってくれますねー
他にもメールアドレス、名前などいろいろFakeしてくれます。

実際はこんな風に使いました。

@a_to_b = Factory.create(:message, :sender_id => @Aさん.id, :recipient_id => @Bさん.id)
@c_to_d = Factory.create(:message, :sender_id => @Cさん.id, :recipient_id => @Dさん.id)


悪くないす。
http://rubyforge.org/projects/faker
Faker: Quick “Fake Data” Generation in Ruby

Authlogic + factory_girlの罠

Railsの認証プラグインではrestful_authentication迫る人気のauthlogicを使い始めました。
それと同時に!!テストはshoulda、fixtureはやめてfactory_girlを使っています。完全に単なる新しい物好きの挙動です。

それぞれ使い方はgithubのドキュメント見ればわかります。authlogicはサンプルアプリが助かりました。

躓いたところがあるので補足します。

functional testを書いてたら、どうもauthlogicでログインが出来ませぬ。

最初は確かこんな感じ。最後の二つ(password_saltとcrypted_password)は、サンプルアプリのfixtureからとってきました
$ cat test/factories.rb


Factory.define :ユーザさん, :class => User do |f|
f.username "ユーザさん"
f.email "ユーザさん@example.com"
f.password "pasuwado"
f.password_confirmation "pasuwado"
f.password_salt (salt = Authlogic::Random.hex_token)
f.crypted_password {Authlogic::CryptoProviders::Sha512.encrypt("sasasa" + salt)}
end


でも、どうもうまくいかない。Factoryで作ったsaltで暗号化されてないっぽい。何でなの?
調べてみると

it's all good, I am not using fixtures but Factories.
Factory.define :user do |u|
u.login Factory.next :login
u.password "password"
u.password_confirmation "password"
end
now it works fine.

だそうで。いいの?saltとか指定しないで?平気でした。Factoryがよろしく作ってくれました。

なので、これでOK。
$ cat test/factories.rb
Factory.define :ユーザさん, :class => User do |f|
f.username "ユーザさん"
f.email "ユーザさん@example.com"
f.password "pasuwado"
f.password_confirmation "pasuwado"
end


さらに。authlogicはユーザー(例えば。acts_as_authenticなモデル)のインスタンスを生成すると勝手にログインしてくれるので、そこも注意です。

$ cat test/functional/user_sessions_controller_test.rb
require 'test_helper'
class UserSessionsControllerTest < ActionController::TestCase
context "UserSessionsController" do
setup do
activate_authlogic
@ユーザさん = Factory.create(:ユーザさん)
UserSession.find.destroy #ログアウトしておく
end
end

Author

Fujimura Daisuke
http://fujimuradaisuke.com

Labels