我一直在遵循模型测试和集成测试的基本模式。我也一直在使用 FactoryGirl 以及 rspec 和 capybara。所以...首先是我的工厂的样子:
FactoryGirl.define do
factory :user do
sequence(:email) { |n| "person#{n}@example.com" }
password "foobar"
password_confirmation "foobar"
end
factory :post do
sequence(:title) { |n| "Test Title #{n}"}
string "Test content."
published_at Time.now()
comments_count 0
draft false
association :user
factory (:draft) do
draft true
end
end
end
然后我会制作一个模型规格文件(spec/models/post_spec.rb):
require 'spec_helper'
describe Post do
let(:post) { FactoryGirl.create(:post) }
subject { post }
it { should respond_to(:title) }
it { should respond_to(:content) }
it { should respond_to(:user_id) }
it { should respond_to(:user) }
it { should respond_to(:published_at) }
it { should respond_to(:draft) }
it { should respond_to(:comments_count) }
its(:draft) { should == false }
its(:comments_count) { should == false }
it { should be_valid }
end
然后我会做一个集成测试(spec/requests/posts_spec.rb):
require 'spec_helper'
describe "Posts pages" do
subject { page }
describe "index page when draft == false" do
let(:post) { FactoryGirl.create(:post) }
before { visit posts_path }
it { should have_content(post.title) }
end
describe "index page when draft == true" do
let(:draft) { FactoryGirl.create(:draft) }
before { visit posts_path }
it { should_not have_content(draft.title) }
end
end
您可以尝试通过http://ruby.railstutorial.org/上的 Rails 教程进行操作,它使用 rspec、capybara 和 FactoryGirl 进行测试。