1

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
Soe Naing
  • 11
  • 4

2 Answers2

1

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.

Billy Chan
  • 24,625
  • 4
  • 52
  • 68
0

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
yfeldblum
  • 65,165
  • 12
  • 129
  • 169
  • Thanks. But it still have an error message that shows connection not established. If you don't mind, can you explain me how to fix??? – Soe Naing Aug 27 '13 at 03:41