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)
それはおそらく勝った:
答えの1つに示唆されているように、「be_present」と「be」の間に違いがありますか? – Godzilla74
'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