Testing your AR models made easy with accepts_values_for
I was looking for an easy way to test my models and I came across this gem
https://github.com/bogdan/accept_values_for
an example taken from here (http://www.christopherbloom.com/2011/07/12/testing-model-validations-in-rspec-the-short-and-sweet-way/)
it "should be required" do
blank = Factory.build(:my_model, :name => "")
blank.should_not be_valid
blank.errors[:name].should include("can't be blank")
blank.name = "Foo"
blank.should be_valid
end
but this looks a lot cleaner and does the same
it { should accept_values_for(:name, "Foo") }
it { should_not accept_values_for(:name, nil) }
Written by Oscar Rieken
Related protips
2 Responses
So much cleaner, thanks for sharing!
over 1 year ago
·
What about using shoulda matchers? They have a matcher which does essentially the same (validate an attribute can't be blank).
it { should validate_presence_of(:name) }
You could combine this with a Factory which has all default values and test if this Factory is valid:
FactoryGirl.define do
factory :my_model do
name "Foo"
end
end
let(:my_model) { FactoryGirl.create(:my_model) }
it { my_model.should be_valid }
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Activerecord
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#