我必須測試一個類別rails模型,與rspec和工廠女孩隔離。我開始定義一個類(記錄)與像FactoryGirl如下:使用RSpec&FactoryGirl在模型中測試rails類方法的正確方法是什麼?
#spec/factories/category.rb
FactoryGirl.define do
factory :category do |f|
f.name "A/B Testing"
f.tags_array %w(test a/b)
end
end
和類別型號規格,如:
# spec/models/category_spec.rb
require 'spec_helper'
describe "Category" do
before(:each) do
@category = FactoryGirl.create(:category)
end
it "has a valid factory" do
@category.should be_valid
end
it "is invalid without a name" do
@category.name = nil
@category.should_not be_valid
end
it "is invalid without at last one tag" do
@category.tags_array = nil
@category.should_not be_valid
end
end
現在我應該定義&試驗,類別類方法其回報a 競爭對手陣列競爭對手這是一個Struct對象,如下所示:
Object.const_set :Competitor, Struct.new(:html_url, :description, :watchers, :forks)
那麼這個類方法seff.find_competitors_by_tags應該返回結構的數組(數組:競爭結構對象):
def self.find_competitors_by_tags(tags_array)
competitors = []
Extractor.each do |wl|
competitors << Competitor.new(wl.html_url, wl.description, wl.watchers, wl.forks)
end
return competitors
end
什麼是使用RSpec & FactoryGirl測試這種隔離的最佳途徑?我覺得像下面這樣,但我不能說清楚:
spec/factories/competitor.rb
FactoryGirl.define do
factory :competitor do |f|
f.html_url "https://github.com/assaf/vanity"
f.description "Experiment Driven Development for Ruby"
f.watchers "844"
f.forks "146"
end
end
# spec/models/category_spec.rb
require 'spec_helper'
describe "Category" do
...
...
it "returns a list of all competitors for each category" do
competitors << FactoryGirl.create(:competitor)
competitors << Factory.build(:competitor, html_url: "https://github.com/andrew/split",
description: "Rack Based AB testing framework",
watchers: "357",
forks: "42")
@category.find_competitors_by_tags("A/B Testing").should == competitors
end
end
它不反正工作,我也不能肯定是否是有意義的:
Failures:
1) Category returns a list of all competitors for each category
Failure/Error: @competitors << FactoryGirl.create(:competitor)
NameError:
uninitialized constant Competitor
# ./spec/models/category_spec.rb:22:in `block (2 levels) in <top (required)>'
什麼測試這種方法的正確方法?
您可以將其發佈到http://codereview.stackexchange.com/,在那裏沒有足夠的ruby/rails問題imho –