33

テストとレールは初めてですが、TDDプロセスを適切にダウンさせようとしています。

has_many :through リレーションシップをテストするために何らかのパラダイムを使用するかどうか疑問に思っていましたか? (または、一般的には has_many だけだと思います)。

たとえば、私のモデル仕様では、関連メソッドの関係の両端をチェックする簡単なテストを確実に書いていることがわかりました。

すなわち:

require 'spec_helper'

describe Post do

  before(:each) do
    @attr = { :subject => "f00 Post Subject", :content => "8ar Post Body Content" }
  end

  describe "validations" do
  ...    
  end

  describe "categorized posts" do

    before(:each) do
      @post  = Post.create!(@attr)
    end

    it "should have a categories method" do
      @post.should respond_to(:categories)
    end

  end

end

次に、カテゴリ仕様で逆テストを行い、@category.posts をチェックします。

他に何が欠けていますか?ありがとう!!

4

4 に答える 4

72

Shouldaという gem をチェックすることをお勧めします。関係や検証などをテストするためのマクロがたくさんあります。

has_many 関係が存在することをテストすることだけが必要な場合は、次のようにすることができます。

describe Post do
  it { should have_many(:categories) }
end

または、has_many :through をテストする場合は、次のようにします。

describe Post do
  it { should have_many(:categories).through(:other_model) }
end

Shoulda Rdocページも非常に役に立ちます。

于 2010-10-20T00:00:50.623 に答える
2
describe "when Book.new is called" do
  before(:each) do
    @book = Book.new
  end

  #otm
  it "should be ok with an associated publisher" do
    @book.publisher = Publisher.new
    @book.should have(:no).errors_on(:publisher)
  end

  it "should have an associated publisher" do
    @book.should have_at_least(1).error_on(:publisher)
  end

  #mtm
  it "should be ok with at least one associated author" do
    @book.authors.build
    @book.should have(:no).errors_on(:authors)
  end

  it "should have at least one associated author" do
    @book.should have_at_least(1).error_on(:authors)
  end

end
于 2011-07-06T04:15:02.243 に答える
2

驚くべきことはこれをうまく行います:

describe Pricing do

  should_have_many :accounts, :through => :account_pricings
  should_have_many :account_pricings
  should_have_many :job_profiles, :through => :job_profile_pricings
  should_have_many :job_profile_pricings

end

通常、モデルから仕様にすべての関係をコピーし、「has」を「should_have」、「belongs_to」を「should_belong_to」などに変更します。レールをテストしているという非難に答えるために、データベースもチェックして、関連付けが機能していることを確認します。

検証をチェックするためのマクロも含まれています。

should_validate_numericality_of :amount, :greater_than_or_equal_to => 0
于 2010-10-20T08:14:16.443 に答える