How to write rspec testing without database in ruby for this ruby code

1.4k Views Asked by At

I am creating a ruby project with the class which is the inheritance of ActiveRecord::Base. How can i write rspec testing and simple coverage for the following code sample without using database.

class Person < ActiveRecord::Base
    validates_length_of :name, within: 10..40
end
person = Person.create(:name => "aungaung")
person.save
2

There are 2 best solutions below

1
On

Here's a short example of testing the validations on an ActiveRecord model. You can certainly go into much more depth, and there are plenty of ways to make the tests more elegant, but this will suffice for a first test.

describe Person do

  describe "#name" do
    specify { Person.new(:name => "Short").should_not be_valid }
    specify { Person.new(:name => "Long" * 12).should_not be_valid }
    specify { Person.new(:name => "Just Right").should be_valid }
  end

end
0
On

If you don't want to touch db, FactoryGirl.build_stubbed is your friend.

> person = FactoryGirl.build_stubbed :person
> person.save!
> #=> person obj
> Person.all
> #=> [] # Not saved in db

So, to test validation

it "validates name at length" do
   person = FactoryGirl.build_stubbed :person, name: "aungaung"
   expect{person.save!}.to raise_error(ActiveRecord::RecordInvalid)
end

Note build_stubbed is good at model's unit testing. For anything UI related, you can't use this method and need to save to db actually.