In order to spec ActiveRecord models. I decided to write a few custom matchers that makes the work match easier:
- accept_values_for
- discover
RSpec matcher to test the validation
describe User do
subject { User.new(@valid_attributes)}
it { should accept_values_for(:email, "[email protected]", "[email protected]") }
it { should_not accept_values_for(:email, "invalid", nil, "a@b", "[email protected]") }
end
RSpec matcher to test named scopes
describe "#by_category_id named scope" do
let(:given_category) do
Factory.create(:given_category)
end
let(:product_in_given_category) do
Factory.create(
:product,
:categories => [given_category]
)
end
let(:product_not_in_given_category) do
Factory.create(
:product,
:categories => [Factory.create(:category)]
)
end
# This might be tricky to redefine subject as the finder result
# but in this way we can delegate the matcher to subject and
# avoid writing test descriptions.
subject { described_class.by_category_id(given_category.id) }
it { should discover(product_in_given_category) }
it { should_not discover(product_not_in_given_category) }
end
- ActiveRecord
- Rspec
gem 'accept_values_for'
require 'accept_values_for'
require 'discover'
Like accept_values_for?
Follow the repository on GitHub.
Read author blog.