写rspec / capybara测试的正确方法?

时间:2013-07-12 01:35:46

标签: ruby-on-rails ruby testing rspec capybara

我是Ruby和Rails的新手,我试图以正确的方式实施测试。我目前正致力于让用户注册。我希望第一个用户注册成为管理员,之后每个用户都是普通用户。

我目前正在考虑将测试作为一项功能编写,但我想知道这是否真的应该是模型测试。

我目前的代码就在这里

require 'spec_helper'

describe "User pages" do
    subject { page }

    describe "Sign up page" do
        before { visit signup_path }

        it { should have_button('Create!') }
    end

    describe "Creating an account" do
        before { visit signup_path }
        let(:submit) { "Create!" }

    describe "with invalid information" do
        it "should not create the user account" do
            expect { click_button "Create!"}.not_to change(User, :count)
        end

        describe "it should display errors" do
            before { click_button submit }

            it { should have_content('Failed signup') }
        end
    end

    describe "with valid information" do
        before do
            fill_in "Name", with: "Example User"
            fill_in "Email", with: "user@example.com"
            fill_in "Password", with: "password"
            fill_in "Confirm Password", with: "password"
        end

        it "should create the user" do
            expect { click_button submit }.to change(User, :count).by(1)
        end

        # User sign in not implemented at this point
        describe "the first user" do
            User.all.count.should == 0
            click_button submit
            User.all.count.should == 1
            @firstUser = User.first
            @firstUser.is_admin?.should == true

            describe "the second user" do
                before do
                    visit signup_path
                    fill_in "Name", with: "Example User2"
                    fill_in "Email", with: "user2@example.com"
                    fill_in "Password", with: "password"
                    fill_in "Confirm Password", with: "password"
                end

                click_button submit
                @secondUser = User.all.last
                @secondUser.is_admin?.should == false
            end
        end
    end
end

我最关心的是"有效的信息"部分,并希望清理它,以便它正确适合rspec / capybara。

1 个答案:

答案 0 :(得分:0)

你可以尝试迈克尔哈特尔这个伟大的tutorial,他在本教程中使用Rspec你可以从中学习:) 我也是初学者,我从它开始:D