33

我是测试和 Rails 的新手,但我正试图让我的 TDD 进程正常运行。

我想知道您是否使用任何范式来测试 has_many :through 关系?(或者我想一般只是 has_many )。

例如,我发现在我的模型规范中,我肯定会编写简单的测试来检查关系的两端是否有相关方法。

IE:

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的宝石。它有很多用于测试关系和验证等内容的宏。

如果您只想测试 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 回答
6

为了完整起见,在 2020 年,这在没有额外宝石的情况下是可能的。

  it "has many categories" do
    should respond_to(:categories)
  end

甚至更明确:

it "belongs to category" do
  t = Post.reflect_on_association(:category)
  expect(t.macro).to eq(:belongs_to)
end

(参见关于反射的 Ruby API

第二个示例确保“has_one”不会与“belongs_to”混淆,反之亦然

但是,它不仅限于 has_many :through 关系,还可以用于应用于模型的任何关联。

(注意:这是在Rails 5.2.4中使用新的 rspec 2.11 语法)

于 2020-03-29T16:55:15.853 回答
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”,等等。为了回答它正在测试 Rails 的指控,它还会检查数据库,确保关联有效。

还包括用于检查验证的宏:

should_validate_numericality_of :amount, :greater_than_or_equal_to => 0
于 2010-10-20T08:14:16.443 回答
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 回答