Rails でテストコードを書くために以下のgemをインストールしました
Gemfile
1group :test do 2 # Adds support for Capybara system testing and selenium driver 3 gem 'capybara', '>= 2.15' 4 gem 'rspec-rails' 5 gem "factory_bot_rails" 6 gem 'faker' 7end 8
下記のようにファイルを作成しました
spec/factories/comment.rb
ファイルに記述した内容
FactoryBot.define do factory :comment do title { 'テストタイトル' } taste { '3' } healthy { '3' } cost_performance { '3' } item_code { 'test:00000' } content { 'テストコンテント' } association :user end end
コメントモデルのテストをするために
comment_spec.rbに
ruby
1RSpec.describe 'Commentモデルのテスト', type: :model do 2 describe 'バリデーションのテスト' do 3 let(:user) { create(:user) } 4 let(:comment) { create(:comment, user_id: user.id) } 5 6 context 'titleカラム' do 7 it '空欄でないこと' do 8 comment.title = '' 9 expect(comment.valid?).to eq false; 10 end 11 it 'タイトルが50文字超だと無効な状態であること' do 12 comment.title = 'a' * 51 13 comment.valid? 14 expect(comment.errors[:title]).to include('は50文字以内で入力してください') 15 end 16 end 17 18 context 'contentカラム' do 19 it '空欄でないこと' do 20 comment.content = '' 21 expect(comment.content.valid?).to eq false; 22 end 23 it '200文字以下であること' do 24 comment.content = Faker::Lorem.characters(number:201) 25 expect(comment.content.valid?).to eq false; 26 end 27 end 28 end 29 30〜〜〜〜以下にも続く
テストを通すと
NameError: undefined local variable or method `content' for #<RSpec::ExampleGroups::Comment::Nested::Content:0x000055a08ad23d10>
大半のエラーがこのように出ています
どこが間違っているのでしょうか
commentは
RSpec.describe 'Commentモデルのテスト', type: :model do describe 'バリデーションのテスト' do let(:user) { create(:user) } let(:comment) { create(:comment, user_id: user.id) }
これで定義できているのだと思っていたのですが
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/05/25 06:04