我正在编写这些规范来测试到达控制器的不同参数。我检测到一些拼写错误以设置性别,并基于此我将用户更新为男性或女性,但我看到它看起来非常重复。
由于参数实际发生在每一个之后,我没有看到如何简化这一点。知道如何简化此代码?
describe "GET #create" do
it { get :create; expect(response).to have_http_status(:success) }
context "Signup Step #1" do
before(:each) do
@user = build(:user)
end
context "Male" do
context "HOMBRE" do
before { get :create, full_message: "hombre", user_name: @user.name }
it { expect(User.last.gender).to eq(:male) }
it { expect(response.body).to have_text("returned text okay") }
it { expect(User.last.messages.count).to eq(3) }
end
context "HOMVRE" do
before { get :create, full_message: "homvre", user_name: @user.name }
it { expect(User.last.gender).to eq(:male) }
it { expect(response.body).to have_text("returned text okay") }
it { expect(User.last.messages.count).to eq(3) }
end
end
context "Female" do
context "MUJER" do
before { get :create, full_message: "mujer", user_name: @user.name }
it { expect(User.last.gender).to eq(:female) }
it { expect(response.body).to have_text("returned text okay") }
it { expect(User.last.messages.count).to eq(3) }
end
context "MUGER" do
before { get :create, full_message: "muger", user_name: @user.name }
it { expect(User.last.gender).to eq(:female) }
it { expect(response.body).to have_text("returned text okay") }
it { expect(User.last.messages.count).to eq(3) }
end
end
end
end
答案 0 :(得分:1)
我不知道您的团队对测试中重复的容忍度,但我使用subject
和let
来减少一些参数重复。
describe "GET #create" do
subject { get :create, params }
context 'with no params' do
let(:params) { {} }
it { expect(response).to have_http_status(:success) }
end
context "Signup Step #1" do
let(:user) { build(:user) }
let(:user_name) { user.name }
context "Male" do
let(:params) { {full_message: full_message, user_name: user_name} }
context "HOMBRE" do
let(:full_message) { "hombre" }
it { expect(User.last.gender).to eq(:male) }
it { expect(response.body).to have_text("returned text okay") }
it { expect(User.last.messages.count).to eq(3) }
end
context "HOMVRE" do
let(:full_message) { "homvre" }
it { expect(User.last.gender).to eq(:male) }
it { expect(response.body).to have_text("returned text okay") }
it { expect(User.last.messages.count).to eq(3) }
end
end
context "Female" do
context "MUJER" do
let(:full_message) { "mujer" }
it { expect(User.last.gender).to eq(:female) }
it { expect(response.body).to have_text("returned text okay") }
it { expect(User.last.messages.count).to eq(3) }
end
context "MUGER" do
let(:full_message) { "muger" }
it { expect(User.last.gender).to eq(:female) }
it { expect(response.body).to have_text("returned text okay") }
it { expect(User.last.messages.count).to eq(3) }
end
end
end
end
您可以使用Rspec的shared examples重构一些期望,但我建议将它们重复。如果/当您需要不同的行为时,可以更轻松地与团队中的其他工程师交流,并且更容易更改。