Skip to content

Instantly share code, notes, and snippets.

@minhquang4334
Created October 30, 2020 00:19
Show Gist options
  • Save minhquang4334/91e3647561e12228d67508c50cabf101 to your computer and use it in GitHub Desktop.
Save minhquang4334/91e3647561e12228d67508c50cabf101 to your computer and use it in GitHub Desktop.
第9章:Shoulda Matcher & Mock & Stub & Tag
def login_as(user)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
end
RSpec.shared_context 'when login required' do
let(:user) { create(:user) }
before do
login_as(user)
end
context 'when current_user is nil' do
before do
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(nil)
end
it 'depends on your spec' do
# actual spec goes here...
end
end
end
RSpec.configure do |config|
config.include_context 'when login required', :require_login
end
require 'rails_helper'
RSpec.describe User, type: :model do
describe "User Model attributes validation" do
context "when valid data" do
it "is valid with a name, provider, uid, and image_url" do
user = build(:user, name: "Aaron Peter", provider: "Google", uid: "3456", image_url: "./quangdeptrai123.png")
expect(user).to be_valid
end
end
context "when use shoulda matcher with valid data" do
it { is_expected.to validate_presence_of :name }
it { is_expected.to validate_presence_of :provider }
it { is_expected.to validate_presence_of :uid }
it { is_expected.to validate_presence_of :image_url }
subject(:user) { create(:user) }
it { is_expected.to validate_uniqueness_of(:provider).scoped_to(:uid) }
end
end
describe "User Model Method validation" do
context "find or create from auth hash" do
it "find user from hash OK" do
auth_hash = {
provider: "google_auth",
uid: "00test",
info: {
nickname: "quang_handsome",
image: "/hihi.png"
}
}
new_user = User.find_or_create_from_auth_hash!(auth_hash)
expect(new_user).to have_attributes(provider: "google_auth", uid: "00test", name: "quang_handsome", image_url: "/hihi.png")
end
it "create user from hash OK" do
auth_hash = {
provider: "google_auth_1",
uid: "00test_1",
info: {
nickname: "quang_handsome",
image: "/hihi.png"
}
}
new_user = User.find_or_create_from_auth_hash!(auth_hash)
expect(new_user).to have_attributes(provider: "google_auth_1", uid: "00test_1", name: "quang_handsome", image_url: "/hihi.png")
end
end
end
describe "testing with mock and stub", focus: true do
context "use mock" do
it "delegates name to the user who created it" do
user = double(:user, name: "Fake User")
event = Event.new
allow(event).to receive(:owner).and_return(user)
expect(event.owner.name).to eq "Fake User"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment