6

私は現在、Userクラスにこのメソッドを持っています:

def self.authenticate(email, password)
  user = User.find_by_email(email)
  (user && user.has_password?(password)) ? user : nil
end

これで rspec テストを実行するにはどうすればよいですか?

を実行しようとしましたがit { responds_to(:authenticate) }、自分自身が認証とは異なると思います。

self私はまだ Rails の初心者であり、キーワードのテスト方法と説明に関するヒントをいただければ幸いです。

4

2 に答える 2

5
describe User do
  let(:user) { User.create(:email => "foo@bar.com", :password => "foo") }

  it "authenticates existing user" do
    User.authenticate(user.email, user.password).should eq(user)
  end

  it "does not authenticate user with wrong password" do
    User.authenticate(user.email, "bar").should be_nil
  end
end
于 2013-03-29T17:28:10.293 に答える
1

@depaの答えは良いですが、代替手段のために、そして私はより短い構文を好むためです:

describe User do
  let(:user) { User.create(:email => email, :password => password) }

  describe "Authentication" do
    subject { User.authenticate(user.email, user.password) }

    context "Given an existing user" do
      let(:email) { "foo@bar.com" }
      context "With a correct password" do
        let(:password) { "foo" }
        it { should eq(user) }
      end
      context "With an incorrect password" do
        let(:password) { "bar" }
        it { should be_nil }
      end
    end
  end
end

sytax に対する私の好みは別として、これには他のスタイルに比べて 2 つの大きな利点があると思います。

  • 特定の値を簡単にオーバーライドできます (password上記で行ったように) 。
  • さらに重要なことは、空白のパスワード、存在しないユーザーなど、テストされていないものを強調表示することです。

そういうわけで、ととの組み合わせはcontext、私にとって、通常のスタイルよりもはるかに優れています。subjectlet

于 2013-03-29T17:56:03.617 に答える