2017-01-26 14 views
0

rspecを初めて使用しているので、うまくいけばこれを正しく説明しています。私はオブジェクトが作成されていることを確認した後、has_one関係を持つ関連オブジェクトが作成されていることを確認します。rspecにアソシエーションが存在するかどうかのテスト

だから、私のコードは、モデルで次のようになります。

class Device < ActiveRecord::Base 
    has_one :scan_option 

    validates_presence_of :name 

    after_create :create_scan_option 

    def create_scan_option 
    self.scan_option.create! 
    end 
end 

を私は、デバイスのための工場があります。私のRSpecのモデル試験で

FactoryGirl.define do 
    serial_number = SecureRandom.uuid.delete("-") 

    factory :device do 
    identifier serial_number 
    name "Device 1" 
    is_registered true 
    timezone "America/Chicago" 
    end 
end 

を私は、コードは次のようになり想像この:

RSpec.describe Device, :type => :model do 
    it "creates a scan_option after_create" do 
    subject = build(:device) 
    # test whether the scan_option object was created and associated with the device? 
    end 
end 

私はRSpecのを理解しようと、shouldaか何かを使用していませんよより良い。

subject = build(:device) 
expect(subject.scan_option).not_to be_nil 

expect { build(:device) }.to change(ScanOption, :count).by(1) 

それはおそらく勝った:

答えて

2

私はこのような何かをするだろうクラス自体が関連付けられたオブジェクトを作成し、ファクトリによって作成されないことを保証します。

+0

答えの1つに示唆されているように、「be_present」と「be」の間に違いがありますか? – Godzilla74

+0

'be_present'は、' scan_option'の 'present?'が 'true'を返すことをテストします。 ['be'](https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/be-matchers)は' scan_option'が真実であることをテストします( 'nil'や' false ')。この例では結果に実際には違いはありませんが、IMOでは 'be_present'を使って読みやすくなります。 – spickermann

0

あなただけのデバイスを保存して、関連付けを呼び出し、それを確認することができるはずですが、何かに

it "creates a scan_option after_create" do 
    subject = build(:device) 

    subject.save 

    expect(subject.scan_option).to be 
end 
0

いくつかの方法を返します。あなたの工場だけを建設したからです。あなたが実際にデータベースに永続化する必要があり、実行するコールバックのために

:私はDevice.createの代わりFactoryGirl.createを使用することになり

subject(:device) { Device.create(attributes_for(:device)) } 

it 'has a scan option' do 
    expect(device.scan_option).to be_present 
end 

subject = create(:device) 
関連する問題