I’d like to find a good way to drive out a belongs_to (or has_many, …) relationship. I know how to write the basic code, but I’m not comfortable with the rspec code I came up with… suggestions for improvement?
require 'spec_helper' describe FeaturedCompany do it "requires a company" do f_company = FeaturedCompany.create article_id: 1 expect(f_company).to have(1).error_on(:company) end it "requires an article" do f_company = FeaturedCompany.create company_id: 1 expect(f_company).to have(1).error_on(:article) end it "has one related company" do f_company = FeaturedCompany.create expect(f_company.company).to be_nil f_company.company = Company.new expect(f_company).to have(:no).errors_on(:company) end it "has one related article" do f_company = FeaturedCompany.create expect(f_company.article).to be_nil f_company.article = Article.new expect(f_company).to have(:no).errors_on(:article) end end
# == Schema Information # # Table name: featured_companies # # id :integer not null, primary key # company_id :integer # article_id :integer # class FeaturedCompany < ActiveRecord::Base attr_accessible :company_id, :article_id belongs_to :company belongs_to :article validates_presence_of :company, :article end
This is after a bit of refactoring… when I first wrote the specs/validations, I started out focusing on company_id and article_id since I was clear about what I wanted there; eventually I refactored out most of the [x]_id into [x] to the sate you see it now. Even though that worked and eventually got me here, I’m not happy with how I did it.