Rails RSpec测试has_many:通过关系
我是新来的测试和rails,但我试图让我的TDD过程正常。Rails RSpec测试has_many:通过关系
我想知道你是否使用任何种类的范例来测试has_many:通过关系? (或只是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
我失去了还有什么?谢谢!!
我建议您查看名为Shoulda的宝石。它有很多宏来测试关系和验证等事情。
如果你想要的是测试的的has_many关系存在,那么你可以做到以下几点:
describe Post do
it { should have_many(:categories) }
end
或者,如果你正在测试的has_many:通过,那么你会使用这样的:
describe Post do
it { should have_many(:categories).through(:other_model) }
end
我觉得Shoulda Rdoc也很有帮助。
remarkable会做到这一点很好:
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
一般来说,你只需复制所有的关系,从模型的规范,改变“有”到“should_have”,“belongs_to的”到“should_belong_to”等等。为了回答测试栏的费用问题,它还会检查数据库,确保该关联正常工作。
宏还包括用于检查验证,以及:
should_validate_numericality_of :amount, :greater_than_or_equal_to => 0
非凡的声音很酷!你用的是rails3 env吗? – 2010-10-20 20:36:49
@Zaz,到目前为止我已经使用Rails 2.2.3和2.3.9。我相信它也适用于Rails 3,但我没有尝试过。 – 2010-10-21 01:59:35
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
在那里你进行测试时,亲手做任何共同的东西?我正在寻找基本的东西,我应该马上开始做。诸如......测试我的关联似乎是合理的,但是我应该通过关联测试每种方法吗?或者如何知道何时停止?大声笑 – 2010-10-20 05:36:59
我真的很喜欢使用这些快速单行测试,因为它们非常易于安装。我总是从这些开始,并添加每个关系和验证,包括所有直通关联。它不需要太多工作,也不会增加测试的开销。然后,当我添加功能时,我会添加更多的单元测试。如果您在编写代码时为模型编写测试,这确实会迫使您编写简单的模块化代码。 – 2010-10-20 12:05:36
如何通过与syntex的关联来编写has_many? – indb 2016-02-17 13:20:57