0

我正在尝试使用 rspec 为我的 rails 应用程序编写测试,我基本上想创建两个实例

1) 计数器值为 0 的用户

2) 计数器值为 5 或更多的用户

这是我的工厂用户代码

FactoryBot.define do
  factory :user do
    sequence(:email) { |n| "user#{n}@abc.com" }
    name 'rishabh agarwal'
    password '12345678'
    counter 0
  end
end

在我写的 user_controller_spec 文件中

context 'get#redeem' do
  it 'should not redeem the account for points lesser than 5' do
    get :redeem, format: :json,params:{:id=>dummyUser.id}
    expect(JSON.parse(response.body)["message"]).to eq("You cannot redeem your points")
   end

  it 'should redeem the account if points are greater than or equal to 5' do                                       
    get :redeem, format: :json,params:{:id=>dummyUser.id}
    json=JSON.parse(response.body)
    expect(JSON.parse(response.body)["counter"]).to eq(5)
  end
end

虽然我曾经let!创建实例 let!(:dummyUser){create :user}

4

3 回答 3

1

这就是我构建测试的方式:

context "get#redeem" do
  before { get :redeem, format: :json, params: { id: user.id } }

  context 'when the user has more than or 5 points' do
    let(:user) { create(:user, counter: 5) }

    it 'redeems the account' do
      json = JSON.parse(response.body)
      expect(json["counter"]).to eq 5
      expect(response.status).to eq 200
    end
  end

  context 'when the user has less than 5 points' do
    let(:user) { create(:user, counter: 4) }

    it 'does not redeem the account' do
      json = JSON.parse(response.body)
      expect(json["message"]).to eq "You cannot redeem your points"
      expect(response.status).to eq 403
    end
  end
end

几点注意事项:

  • 不确定 403 响应代码,您可能希望使用不同的响应代码。
  • json_response考虑提取为您的测试调用的方法,如下所示:
def json_response
  @json_response ||= JSON.parse(response.body)
end
于 2018-11-14T05:47:49.643 回答
0

找到了一种更好的方法....只需在工厂中将计数器变量初始化为 0 并在使用上下文超过 5 时更改计数器 dummyUser.counter=5 dummyUser.save 的值,这会将值更改为 5 并且可以使用由测试用例。

于 2018-11-14T06:09:10.053 回答
0

您可以简单地在 create 方法中传递属性

create(:user, counter: 5)
于 2018-11-14T07:39:11.777 回答