Rails 3.1, RSpec: testing model validations

后端 未结 7 1721
不知归路
不知归路 2021-01-30 03:51

I have started my journey with TDD in Rails and have run into a small issue regarding tests for model validations that I can\'t seem to find a solution to. Let\'s say I have a U

7条回答
  •  臣服心动
    2021-01-30 04:33

    CONGRATULATIONS on you endeavor into TDD with ROR I promise once you get going you will not look back.

    The simplest quick and dirty solution will be to generate a new valid model before each of your tests like this:

     before(:each) do
        @user = User.new
        @user.username = "a valid username"
     end
    

    BUT what I suggest is you set up factories for all your models that will generate a valid model for you automatically and then you can muddle with individual attributes and see if your validation. I like to use FactoryGirl for this:

    Basically once you get set up your test would look something like this:

    it "should have valid factory" do
        FactoryGirl.build(:user).should be_valid
    end
    
    it "should require a username" do
        FactoryGirl.build(:user, :username => "").should_not be_valid
    end
    

    Oh ya and here is a good railscast that explains it all better than me:

    good luck :)


    UPDATE: As of version 3.0 the syntax for factory girl has changed. I have amended my sample code to reflect this.

提交回复
热议问题