2015-08-31 110 views
2

請幫助測試協會。我有型號:如何在rails中測試關聯?

class Album < ActiveRecord::Base 
    belongs_to :user 
end 

class User < ActiveRecord::Base 
    has_many :albums, dependent: :destroy 
end 

我嘗試測試協會:

describe Album do 
    describe 'associations' do 
    it "belongs_to user" do 
     should belongs_to(:user) 
    end 
    end 
end 

在控制檯中運行測試後,我得到如下:

Failures: 1) Album associations belongs_to user Failure/Error: should belongs_to(:user) NoMethodError: undefined method belongs_to' for #<RSpec::ExampleGroups::Album::Associations:0x0000000762bc98> # ./spec/models/album_spec.rb:36:in block (3 levels) in '

Finished in 1.41 seconds (files took 2.32 seconds to load) 7 examples, 1 failure Failed examples: rspec ./spec/models/album_spec.rb:35 # Album associations belongs_to user

回答

1

您可以測試該關聯容易使用belong_to匹配的寶石shoulda

describe Album do 
    it { should belong_to(:user) } 
end 

請參閱this for an example