I installed Fabrication and Faker in my Rails 4 project

I created a fabrarication object:

Fabricator(:course) do
  title { Faker::Lorem.words(5) }
  description { Faker::Lorem.paragraph(2) } 
end

And I'm calling the Faker object within my courses_controller_spec.rb test:

require 'spec_helper'

describe CoursesController do
  describe "GET #show" do
    it "set @course" do
      course = Fabricate(:course)
      get :show, id: course.id
      expect(assigns(:course)).to eq(course)
    end
    it "renders the show template"
  end
end

But for some reason, the test failes at line 6:

course = Fabricate(:course)

the error message is:

Failure/Error: course = Fabricate(:course)
 TypeError:
   can't cast Array to string

Don't know exactly why this is failing. Has anyone experienced the same error message with Faker?

有帮助吗?

解决方案

The return from words(5) is an array, not a string. You should do this:

title { Faker::Lorem.words(5).join(" ") }

其他提示

Not sure if this was available back then, but another solution would be to give it a sentence instead of a word:

From the repo

def sentence(word_count = 4, supplemental = false, random_words_to_add     = 6)
    words(word_count + rand(random_words_to_add.to_i).to_i, supplemental).join(' ').capitalize + '.'
end

So you could do:

Faker::Lorem.sentence(5, false, 0)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top