开发者

How should I test a model with a lot of attributes and validations in Ruby on Rails?

开发者 https://www.devze.com 2023-01-21 15:23 出处:网络
Hi I have a user model with a lot of attributes and validati开发者_开发知识库on that I require to go in.

Hi I have a user model with a lot of attributes and validati开发者_开发知识库on that I require to go in. I want to develop my application using test-driven development but am having a hard time writing simple tests for validations such as no blank emails, unique emails, proper email address.

So what's the best way to start writing tests?


Shoulda ( http://github.com/thoughtbot/shoulda/wiki/Usage ) will allow checking of such ActiveRecord checks easily.

  should_not_allow_values_for :email, "blah", "b lah" 
  should_allow_values_for :email, "a@b.com", "asdf@asdf.com" 

Its reasonably clear what the code does and it includes a fair few useful checks like these.


Create a hash of valid attributes that will successfully create an object of the type you wish to test. This is typically done once in a before step. Then, for each attribute you want to check validations on create a test sort of like this (using rSpec syntax):

obj_under_test = MyModel.new(@valid_attributes)
object_under_test.email = nil
obj_under_test.should_not be_valid

In this case @valid_attributes is a hash you create. An alternative to this is to use sensible factories to generate your objects for each test. Look at FactoryGirl, Machinist, Fixjour for some examples. So using your example, something like this makes sense:

You can drive your tests/specs out to the level of granularity you like. Many people like to test only one thing per case (or "example", in BDD parlance). So you may have a forest of tests like "should have an email supplied", "should have a valid email if one is supplied", "should have an email at a valid domain", etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消