woshidan/sample_app — pull request #6 by woshidan (2014-03-01 01:43:45+00:00)
Title: マイクロポスト作成エラー

問題

テストで以下のようにmicropostをbuildしたら自動的にuser_idにuser.idが入っているはずなのにnil

原因？

userの生成ができていないか、属性がおかしい？

テスト

spec/models/micropost_spec.rb

let(:user) { FactoryGirl.create(:user) } #この行からおかしい？
before do
@micropost = user.microposts.build(content: "Lorem ipsum")
end

subject { @micropost }

it { should respond_to(:content) }
it { should respond_to(:user_id) }
it { should respond_to(:user) }
its(:user) { should eq user}

it { should be_valid }

エラー

1) Micropost
Failure/Error: it { should be_valid }
expected # to be valid, but got errors: Content can't be blank
# ./spec/models/micropost_spec.rb:16:in `block (2 levels) in '

ユーザのモデル

spp/models/user.rb (<は入れるとおかしくなるのでextendsで代用)

class User extends ActiveRecord::Base
has_many :microposts, dependent: :destroy
attr_accessible :name, :email, :password, :password_confirmation
before_save { self.email = email.downcase }
before_create :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive:false }
has_secure_password
validates :password, length: { minimum: 6 }

def User.new_remember_token
SecureRandom.urlsafe_base64
end

def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end

private

def create_remember_token
self.remember_token = User.encrypt(User.new_remember_token)
end
end

マイクロポストのモデル

app/models.micropost.rb

class Micropost extends ActiveRecord::Base
belongs_to :user
default_scope -> { order('created_at DESC') }
validates :user_id, presence: true
validates :content, presence: true, length: { maximum: 140 }
end