4

I am new to rails and testing models. My model class is like this:

class Tester < Person
  has_one :company
  accepts_nested_attributes_for :skill   
end

And I want to do test for "accepts_nested_attributes_for :skill" using rspec with out any other gem. How can I accomplish this?

1 Answer 1

6

There are convenient shoulda gem matchers for testing accepts_nested_attributes_for, but you mentioned that you don't want to use other gems. So, using Rspec only, the idea is to set attributes hash that would include required Tester attributes and nested hash called skill_attributes that would include required Skill attributes; then pass it into create method of Tester, and see if it changes the number of Testers and number of Skills. Something like that:

class Tester < Person
  has_one :company
  accepts_nested_attributes_for :skill
  # lets say tester only has name required;
  # don't forget to  add :skill to attr_accessible
  attr_accessible :name, :skill
  .......................
 end

Your tests:

 # spec/models/tester_spec.rb
 ......
 describe "creating Tester with valid attributes and nested Skill attributes" do
   before(:each) do
     # let's say skill has languages and experience attributes required
     # you can also get attributes differently, e.g. factory
     @attrs = {name: "Tester Testov", skill_attributes: {languages: "Ruby, Python", experience: "3 years"}}
   end

   it "should change the number of Testers by 1" do
      lambda do
        Tester.create(@attrs)
      end.should change(Tester, :count).by(1)
   end

   it "should change the number of Skills by 1" do
      lambda do
        Tester.create(@attrs)
      end.should change(Skills, :count).by(1)
   end
 end

Hash syntax may be different. Also, if you have any uniqueness validations, make sure you are generating @attrs hash dynamically before every test. Cheers, mate.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.