0

我有一个用户控制器,我想测试索引页面,我正在寻找 michael hart'l 的 rails 教程示例,我复制它,这是测试(主要是索引页面显示所有用户,测试看看用户是否是管理员,如果是,用户应该有一个“删除”链接,允许管理员销毁他们):

require 'spec_helper'

describe "user pages" do
  subject { page }

  describe "index" do
    let(:user) { FactoryGirl.create(:user) }
    before(:each) do
      sign_in user
      visit users_path
    end

    it { should have_title('Users') }
    it { should have_content('Users') }

    describe "delete links" do
      it { should_not have_link("delete") } 
      describe "as an admin user" do
        let(:admin) { FactoryGirl.create(:admin) }
        before do
          sign_in admin
          visit users_path
        end
        it { should have_link("delete", href: user_path(User.first)) }
        it "should be able to delete another user" do
        expect do
          click_link('delete', match: :first)
        end.to change(User, :count).by(-1)
      end
      it { should_not have_link('delete', href: user_path(admin)) }
    end
  end
end

我的用户工厂是这样定义的:

FactoryGirl.define do
 factory :user do
   sequence(:name)  { |n| "Person #{n}" }
   sequence(:email) { |n| "person_#{n}@example.com"}
   password "foobar"
   password_confirmation "foobar"
   factory :admin do
      admin true
   end
 end
end

这里没有问题,所有测试也都通过了。但是当我评论或我从上面的测试中删除以下行时:

let(:user) { FactoryGirl.create(:user) }
before(:each) do
   sign_in user
   visit users_get_path
end

它给了我错误:

 1) user pages index delete links as an admin user 
 Failure/Error: it { should have_link("delete", href: user_path(User.first)) }
   expected #has_link?("delete", {:href=>"/users/2395"}) to return true, got false
 # ./spec/requests/user_pages_spec.rb:40:in `block (5 levels) in <top (required)>'

 2) user pages index delete links as an admin user should be able to delete another user
 Failure/Error: click_link('delete', match: :first)
 Capybara::ElementNotFound:
   Unable to find link "delete"
 # ./spec/requests/user_pages_spec.rb:43:in `block (6 levels) in <top (required)>'
 # ./spec/requests/user_pages_spec.rb:42:in `block (5 levels) in <top (required)>'

我在这里不明白为什么它会失败,以及第一个 before 块与“删除链接”块中的其他示例之间的关系是什么?我需要一个简单的解释,谢谢

4

1 回答 1

2

let被延迟评估并且user在您的“删除链接”示例中未引用,因此如果没有第一个before块,则不会创建常规用户并且不存在相应的删除链接,从而导致测试失败。更改首字母letlet!避免此问题。

于 2013-08-14T20:42:56.987 回答