根据Ryan Bates的说法一直在学习Rspec,Capybara和FactoryGirl。 "我如何测试" railscast并遇到障碍。我的应用程序使用Devise进行身份验证,使用CanCan进行授权。我想测试以确保用户可以删除自己的帖子,但不能删除其他用户的帖子,但我似乎无法删除。我已经读过如何使用"控制器测试"对于这一点,谷歌搜索并没有详细说明它与我的集成测试之间的差异以及我如何走这条路。
这是我的代码,下面是结果:
工厂:
2 FactoryGirl.define do
3 factory :role do
4 factory :admin_role do
5 name 'admin'
6 end
7
8 factory :author_role do
9 name 'author'
10 end
...
17 sequence(:name) { |n| "Joe User #{n}"}
18 sequence(:email) { |n| "joeuser+user#{n}@example.com"}
19
20 factory :user do
21 name
22 email
23 password 'secret'
24
25 factory :admin, :class => User do
26 name
27 email
28 after_create { |user| user.roles << FactoryGirl.create(:admin_role) }
29 end
30
31 factory :author , :class => User do
32 name
33 email
34 after_create { |user| user.roles << FactoryGirl.create(:author_role) }
35 end
36 end
37
38 sequence(:title) { |n| "Post Title #{n}"}
39 sequence(:body) { |n| "The inner post body #{n}"}
40
41 factory :post do
42 title
43 body
44 end
45
46 end
posts_spec.rb:
1 require 'spec_helper'
2
3 def login(user)
4 visit new_user_session_path
5 fill_in "Email", :with => user.email
6 fill_in "Password", :with => user.password
7 click_button "Sign in"
8 page.should have_content("Signed in successfully")
9 end
10
11 describe "Posts" do
12 let(:author) {FactoryGirl.create(:author)}
13 let(:author2) {FactoryGirl.create(:author)}
14 let(:user) {FactoryGirl.create(:user)}
15 let(:admin) {FactoryGirl.create(:admin)}
16 let(:post) { FactoryGirl.create(:post, user: author) }
...
99 describe "destroy /post/:id" do
100 it "should allow the author to destroy post" do
101 login(author)
102
103 visit post_path(post, :method => :delete)
104 lambda {
105 visit post_path(post)
106 }.should raise_exception(ActiveRecord::RecordNotFound)
107 end
108 end
109 end
警卫的结果:
Running: spec/requests/posts_spec.rb
........F
Failures:
1) Posts destroy /post/:id should allow the author to destroy post
Failure/Error: lambda {
expected ActiveRecord::RecordNotFound but nothing was raised
# ./spec/requests/posts_spec.rb:104:in `block (3 levels) in <top (required)>'
当我实际使用save_and_open_page(使用launchy)时,我发现该帖子尚未被删除。关于我应该如何做到这一点的任何想法?非常感谢!
答案 0 :(得分:0)
谢谢你,railscard,解决方案:
你真的想通过Capybara测试能力吗?关于测试CanCan的解决方案:github.com/ryanb/cancan/wiki/Testing-Abilities