Rails/Rspec - 为belongs_to关联的类名编写规范

ker*_*lin 5 associations rspec-rails

鉴于以下代码:

(1)你如何编写一个规范来测试home_team和away_team的类名应该是Team类?

(2)你是否还要费心去编写这样的规范?我不确定这样做有什么价值,但想得到你的想法.

class Event < ActiveRecord::Base

  belongs_to :home_team, :class_name => 'Team', :foreign_key => :home_team_id
  belongs_to :away_team, :class_name => 'Team', :foreign_key => :away_team_id

end

describe Event do

  it { should belong_to(:home_team) }
  it { should belong_to(:away_team) }

end
Run Code Online (Sandbox Code Playgroud)

如果应该有这样的东西会很好:

it { should belong_to(:home_team).with_class_name(:team) }
Run Code Online (Sandbox Code Playgroud)

tom*_*nor 6

shoulda-matchers 来源判断,你应该能够做类似的事情......

it { should belong_to(:home_team).class_name(:team) }
Run Code Online (Sandbox Code Playgroud)

或者

it { should belong_to(:home_team).class_name('Team') }
Run Code Online (Sandbox Code Playgroud)


The*_*hop 5

这是一篇关于为什么不应该这样做的博客文章:

http://blog.davidchelimsky.net/2012/02/12/validations-are-behavior-associations-are-structure/

总而言之,关联是应用程序的结构.RSpec旨在测试行为.因此,如果您为从home_team或away_team派生的行为编写测试,它可能会更好.

例如,如果您想要home_team的名称.如果你写一个像这样的方法会更好:

def home_team_name
  home_team.name
end
Run Code Online (Sandbox Code Playgroud)

这是事件类将要求home_team执行的行为.你可以写一个如下的规范:

describe '#home_team_name' do
  before do
    @home_team = Team.new(:name => 'The Home Team')
    @event = Event.new(home_team_id: @home_team.id)
  end

  it 'should return the name of the home team' do
    @event.home_team_name.should == 'The Home Team'
  end
end 
Run Code Online (Sandbox Code Playgroud)

这将是测试关联行为的一个很好的例子,而不直接测试应用程序的结构.

另外,作为一个观点,Rails期望home_team属于'Team'类,并且不需要测试框架,它经过了充分的测试和记录.如果您需要提高对关联工作方式的理解,那么我可以看到这样做的唯一方法是暂时的.