Reputation: 9407
I am using Rspec in Rails. I am currently testing one of my models. This specific model is seeded into the database with 5 records. Each record has a name attribute with a seeded value. For example:
def self.seed
find_or_create_by(name: 'Text')
find_or_create_by(name: 'Number')
find_or_create_by(name: 'Date')
find_or_create_by(name: 'Time')
find_or_create_by(name: 'Boolean')
end
I want to test the creation of each one in Rspec. And currently I am doing this:
describe FieldType, type: :model do
context "when :name is text" do
let(:field_type) { FieldType.create(name: "Text") }
it { expect(field_type).to be_persisted }
it { expect(field_type.name).to eq("Text")}
it { expect(field_type.type_from_field).to be(String) }
end
context "when :name is number" do
let(:field_type) { FieldType.create(name: "Number") }
it { expect(field_type).to be_persisted }
it { expect(field_type.name).to eq("Number")}
it { expect(field_type.type_from_field).to be(Integer) }
end
...
Is this the right way to test this behavior? Or is there a more efficient way to do it?
Upvotes: 0
Views: 62
Reputation: 15945
It looks like the System Under Test here is the method .seed
; so, maybe something like this:
describe FieldType do
describe '.seed' do
before do
described_class.seed
end
it 'creates the expected records' do
expect(described_class.pluck(:name)).to match_array(['Text', 'Number', 'Date', 'Time', 'Boolean'])
end
end
end
Also please check Better Specs for some recommendations and rubocop-rspec for automatically checking your code against some RSpec best practices.
Upvotes: 2