测试此post模型的草稿属性(Rspec + Capybara)

我想用Rspec和Capybara写一个测试。

我有一个Post模型,我想为它添加一个draft属性。 如果用户检查该字段,则将post保存为草稿( draft = true )。 只有属性draft = false的post才会显示在post索引页面中。 draft = truepost只会显示在创建该post的用户的页面中。

在我的生命中,我从未做过Rspec + Capybara测试。 所以我想知道是否有人可以告诉我如何开始或给我一个例子。 提前致谢!

schema.rb:

  create_table "posts", :force => true do |t| t.string "title" t.string "content" t.integer "user_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "comments_count", :default => 0, :null => false t.datetime "published_at" t.boolean "draft", :default => false end 

(顺便说一下,我是否需要发布模型,控制器或视图页面?)

要添加到new2ruby的答案,您还可以在集成测试中使用capybara提供的Feature / Scenario别名。

我发现它很好看:

 require 'spec_helper' feature 'Visitor views posts' do scenario 'shows completed posts' do post = FactoryGirl.create(post) visit posts_path page.should have_content(post.title) end scenario 'does not show drafts' do draft = FactoryGirl.create(draft) visit posts_path page.should_not have_content(draft.title) end end 

我最近写了一篇关于使用RSpec和Capybara进行集成测试的“入门”博客文章。 如果您对设置代码库有任何疑问,请与我们联系。

我一直在遵循模型测试和集成测试的基本模式。 我也一直在使用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文件(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进行测试。