1
votes

I am trying to create a rspec test for a model for States. This state model has an association to a Country model. My factories look like

Factory.define :country do |country|
  country.name  "Test Country"
end

Factory.define :state do |state|
  state.name "Test State"
  state.association :country
end

I have made a functional state model rspec but I am not sure if the way I set up the state @attr is correct or a hack

require 'spec_helper'

describe State do
  before(:each) do
    country = Factory(:country)
    @attr = { :name => 'Test State', :country_id => country.id }
  end

  it "should create a new state given valid attributes" do
    State.create!(@attr)
  end  
end

Being new to rails/rspec I'm unsure if forcibly saying :country_id => country.id is correct or a cheap way of solving the issue. I appreciate any help or suggestions I can get.

I am also including both models just in case.

class Country < ActiveRecord::Base
  has_many :states
  attr_accessible :name

  validates :name,  :presence => true,
                    :uniqueness => {:case_sensitive => false}
end

class State < ActiveRecord::Base
  belongs_to :country

  attr_accessible :name, :country_id

  validates :name,  :presence => true,
                    :uniqueness => {:case_sensitive => false, :scope => :country_id}

  validates :country_id, :presence => true
end
1

1 Answers

2
votes

This is a good start, but your test isn't actually testing anything. As a general rule, you should always have one "should" call per "it" block.

Here's another way of looking at it, assuming the same factories and models:

require 'spec_helper'

describe State do
  before(:each) do
    @state = Factory.build(:state)
  end

  it "should create a new state given valid attributes" do
    @state.save.should be_true
  end
end