Skip to content

Instantly share code, notes, and snippets.

@jacobsmith
Created December 17, 2013 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacobsmith/7998115 to your computer and use it in GitHub Desktop.
Save jacobsmith/7998115 to your computer and use it in GitHub Desktop.
require 'spec_helper'
describe Student do
before do
@student = FactoryGirl.create(:student)
end
subject { @student }
it { should respond_to(:name) }
it { should respond_to(:section) }
describe "should be invalid" do
describe "without name" do
before { @student.name = nil }
it { should_not be_valid}
end
describe "without section" do
before { @student.section = nil }
it { should_not be_valid}
end
end #describe "should be invalid"
describe "it should have an assignment" do
before do
student_assignment = FactoryGirl.create(:assignment)
end
@student.assignment.name.should eq "Homework"
end #describe "it should have an assignment"
end #describe Student
@adamcooper
Copy link

A couple points

  • The @student.assignment.name... needs to be wrapped in an it block to be considered a test.
  • The assignment needs to be associated to a student in order to retrieve it.
  • You can use named subject subject(:student) { FactoryGirl.create(:student) } instead of the before block and subject.
# models
class Student < ActiveRecord::Base
  has_one :assignment
  validates_presence_of :name
  validates_presence_of :section
end

class Assignment < ActiveRecord::Base
  belongs_to :student
end

# in the migrations
create_table :students do |t|
  t.string :name, :section
  t.timestamps
end
create_table :assignments do |t|
  t.references :student
  # t.string :answer # or whatever columns are on this table
  t.timestamp
end
require 'spec_helper'

describe Student do

  subject(:student) { FactoryGirl.create(:student) }

  # these are redundant tests as they are inferred from the validation tests
  it { should respond_to(:name) }
  it { should respond_to(:section) }

  describe "should be invalid" do
    describe "without name" do
      subject(:student) { FactoryGirl.build(:student, name: nil) }
      it { should_not be_valid}
    end

    describe "without section" do
      subject(:student) { FactoryGirl.build(:student, section: nil) }
      it { should_not be_valid}
    end
  end #describe "should be invalid"

  # testing associations is unnecessary as there is no need to test active record internals.
  describe "it should have an assignment" do
    it "associates assignments" do
      student.assignment = FactoryGirl.create(:assignment)
      expect(student.assignment.name).to eq("Homework")
    end
  end #describe "it should have an assignment"
end #describe Student

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment